Singleton mode passeddispatch_once
Implementation, throughsharedInstance
. (The content of GCD will be supplemented later)Next we willDataManager
Add a variable:species
, Type:[String:[String]]
. Ininit()
Add some initialization work:
var species: [String:[String]]init() { let userDefaults = NSUserDefaults.standardUserDefaults() if let speciesInfo = userDefaults.valueForKey("species") as? [String:[String]] { species = speciesInfo } else { species = [ "Birds": ["Swift"], "Cats" : ["Persian Cat"], "Dogs" : ["Labrador Retriever"] ] }}
We can useDataManager.sharedInstance.species
Obtain data of various types.
Tips: code Snippets that may be used multiple times, similar to the singleton mode. We recommend that you add them to Xcode's Snippets.
Step 2: load the listWe store data in the dictionary, and it is very convenient to obtain data through the key value. However, the dictionary itself is unordered, and the data in the list such as UITableView is ordered. So add a computing attributespeciesList
, You can get the sorted list and return:
var speciesList: [String] { var list: [String] = [] for speciesName in species.keys { list.append(speciesName) } list.sort(<) return list}
BackSpeciesViewController
We can obtain the data as follows:
var species: [String] = DataManager.sharedInstance.speciesList
Step 2: List ViewDrag and DropUITableView
, The specific process will not be repeated, you can open the project to see.tableview
The related code is as follows:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell cell.textLabel?.text = species[indexPath.row] return cell}func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return species.count}
Run it to make sure there is no problem. (This is not a question of accomplishment. Test the connection between sb and code .)
Step 2: Details pageCreate anotherRacesViewController
To display the data list of the current type:
class RacesViewController: UIViewController { var species: String! override func viewDidLoad() { super.viewDidLoad() title = species }}
Note: set this in StoryBoardRacesViewController
The StoryBoard ID, so that we can obtainRacesViewController
Then proceedpushViewController
Operation.
Step 2: select an eventBackSpeciesViewController
To add the selected events of cells:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) var racesViewController = storyboard?.instantiateViewControllerWithIdentifier("RacesViewController") as RacesViewController racesViewController.species = species[indexPath.row] navigationController?.pushViewController(racesViewController, animated: true)}
instantiateViewControllerWithIdentifier
You can use the StoryBoard ID to initialize ViewController.
Step 1: display typesThis step is basically the same as step 2,tableview
Related code:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return races.count}func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("RaceCell") as UITableViewCell cell.textLabel?.text = races[indexPath.row] cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell}
Test the function again. Click cell to jump to another table list.
Step 2: Save changes
ToDataManager
Add a method:
func saveData() { let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setValue(species, forKey: "species")}func addRace(species inSpecies: String, race: String) { if var races = species[inSpecies] { races.append(race) species[inSpecies] = races } saveData()}
saveData
Method is used to write data locally,addRace
Add a record for external calls.
Step 2: Add buttonAdd the Add button to the navigation bar and associate itdidTapAdd
ThisIBAction
.
Step 2: pop up the viewUseUIAlerView
The input content of the view is displayed. Note that the style is setPlainTextInput
, Set delegate to self.
@IBAction func didTapAdd() { var alert = UIAlertView(title: "New Race", message: "Type in a new race", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Add") alert.alertViewStyle = UIAlertViewStyle.PlainTextInput alert.show()}
Then implementalertView
Delegate method:
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if buttonIndex == 1 { var textField = alertView.textFieldAtIndex(0)! var newRace = textField.text DataManager.sharedInstance.addRace(species: species, race: newRace) var newIndexPath = NSIndexPath(forRow: races.count - 1, inSection: 0) myTableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic) }}
Then run the following command to test whether the function is OK.
Step 2: delete dataJust like adding data, add a data deletion method to DataManager first:
func removeRace(species inSpecies: String, race inRace: String) { if var races = species[inSpecies] { var index = -1 for (idx, race) in enumerate(races) { if race == inRace { index = idx break } } if index != -1 { races.removeAtIndex(index) species[inSpecies] = races saveData() } }}
There are several notes:
- Pass
index
Set-1 as the identifier to prevent the final result that is not found.
- Pass
enumerate
To traverse the array.++i
You can obtain the index value.Then returnRacesViewController
, Add and delete related delegation methods:
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true}func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { var raceToRemove = races[indexPath.row] DataManager.sharedInstance.removeRace(species: species, race: raceToRemove) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)}
Try the delete operation. OK is OK.
EndThere are no highlights in the following WebView content, which are similar and no longer recorded.
Some key points are recorded in a rush. For more information, see the reference tutorial.
In fact, the function of the entire project is very simple, but you can try the development ideas and basic steps of other programmers by taking the steps from the beginning to the end. In short, there are still some gains. However, the efficiency of viewing and recording is too low. In the future, only key gains will be recorded, and repeated content will not be repeated.
Complete Code address: BirdsCatsDogs
References