[Swift] Day18 & amp; 19: A simple example

Source: Internet
Author: User

[Swift] Day18 & amp; 19: A simple example
Swift90Days-step 1 of a simple small application: Clarify the task

After learning the basic syntax, we can finally get started. Taking this article as an example, we will create a simple application:

  • PassUITableViewShow three small animals
  • PassNSUserDefaultsData Persistence
  • PassUIWebViewLoad more data from Wikipedia

    Due to limited time, this blog is not a tutorial or translation, but a key line of thinking and record. The complete source code is linked at the end of the article. If you have any questions, please contact me. Thank you.

    Step 2: Create a project

    Create a new project and selectSingle View ApplicationThe project name is BirdsCatsDogs.

    Step 2: simple reconstruction

    The system automatically generatesViewController.swift, Change itSpeciesViewController.swiftRemember to change the class name. Then set it in the StoryBoard (later referred to as "SB" and do not misunderstand it)custum classIf the setting is correct and Automatic completion is provided during input, press Enter.

    Step 2: add navigation

    Drag a UINavigationController to SB and set itInitial View Controller, And thenSpeciesViewControllerSet to itsroot view controller. SetSpeciesViewControllerSet the titleSpecies.

    Run it to make sure there is no problem. (It is impossible to have problems. Running at this time is generally to satisfy your own sense of accomplishment .)

    Step 2: load data

    Here we useNSUserDefaultsLoad data. It is usually used to store some system configurations, such as the font size.

    CreateDataManager.swiftTo implement a data manager in singleton mode:

    import Foundationclass DataManager {    struct Static {        static var onceToken : dispatch_once_t = 0        static var instance : DataManager? = nil    }    class var sharedInstance : DataManager {        dispatch_once(&Static.onceToken) {            Static.instance = DataManager()        }        return Static.instance!    }}

    This code is the original code. For details, refer:

    • Static variables are embeddedStaticStructured Storage.
    • Singleton mode passeddispatch_onceImplementation, throughsharedInstance. (The content of GCD will be supplemented later)

      Next we willDataManagerAdd 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.speciesObtain 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 list

      We 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}

      BackSpeciesViewControllerWe can obtain the data as follows:

      var species: [String] = DataManager.sharedInstance.speciesList
      Step 2: List View

      Drag and DropUITableView, The specific process will not be repeated, you can open the project to see.tableviewThe 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 page

      Create anotherRacesViewControllerTo 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 StoryBoardRacesViewControllerThe StoryBoard ID, so that we can obtainRacesViewControllerThen proceedpushViewControllerOperation.

      Step 2: select an event

      BackSpeciesViewControllerTo 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)}

      instantiateViewControllerWithIdentifierYou can use the StoryBoard ID to initialize ViewController.

      Step 1: display types

      This step is basically the same as step 2,tableviewRelated 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

      ToDataManagerAdd 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()}

      saveDataMethod is used to write data locally,addRaceAdd a record for external calls.

      Step 2: Add button

      Add the Add button to the navigation bar and associate itdidTapAddThisIBAction.

      Step 2: pop up the view

      UseUIAlerViewThe 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 implementalertViewDelegate 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 data

      Just 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:

      • PassindexSet-1 as the identifier to prevent the final result that is not found.
      • PassenumerateTo traverse the array.++iYou 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.

        End

        There 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
        • Birds, Cats and Dogs




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.