Explanation of swift 22 ----------- basic usage of UINavigationController and page value passing methods, viewcontroller. swift

Source: Internet
Author: User

Explanation of swift 22 ----------- basic usage of UINavigationController and page value passing methods, viewcontroller. swift
Basic usage of UINavigationController and page value passing Methods

This article introduces the basic usage of UINavigationController, because it involves multiple pages and introduces page value passing.

1. Handwriting code creation UINavigationController

It is easy to create by hand. First, create a project. By defaultstoryboardLoaded. In this case, the default loading mode is removed first.

ThenAppDelegate.swiftOfdidFinishLaunchingWithOptionsCreate
The Code is as follows:

Func application (application: UIApplication, didfinishlaunchingwitexceptions launchOptions: [NSObject: AnyObject]?) -> Bool {// Override point for customization after application launch. // use the code here to create the NavigationController window = UIWindow (frame: UIScreen. mainScreen (). bounds) window ?. MakeKeyAndVisible () UINavigationBar. appearance (). tintColor = UIColor. whiteColor () UINavigationBar. appearance (). barTintColor = UIColor (red: 231.0/255.0, green: 95.0/255.0, blue: 53.0/255.0, alpha: 0.3) // modify the background color of the navigation bar UINavigationBar. appearance (). titleTextAttributes = [NSForegroundColorAttributeName: UIColor. whiteColor ()] // set the font color for the navigation bar. let rootCv = ViewController (); let nav = UINavigationController (rootVi EwController: rootCv) window ?. RootViewController = nav return true}

Don't take a look at so much code, but not so much.UINavigationBarIt starts with the style set for this navigation bar. Do not use the default one. There are five rows and the first two rows are created.windowAnd letwindowDisplay, create a navigation controller in the last three lines, set the controller, andwindowSet the root controller of to this navigation controller. In this case, OK.

After running the program, a black box is displayed, which solves the problem and sets the background color. And then addBarButtonItemOr something.

Self. view. backgroundColor = UIColor. whiteColor () self. navigationItem. rightBarButtonItem = UIBarButtonItem (title: "Next", style :. plain, target: self, action: "goNext:") self. title = "navigation title" // set the title of the navigation bar (not self. navigationController ?. Title Oh !) Self. navigationItem. backBarButtonItem = UIBarButtonItem (title: "I modified the returned result", style:. Plain, target: nil, action: nil)

The last sentence here is to modify the returnedBarButtonItemText. Here the title is set and a new one is added.rightBarButtonItemRegistered eventgoNextLet's implement it.

Func goNext (sender: AnyObject) {print ("") let mainVc = UIStoryboard (name: "Third", bundle: nil ). instantiateViewControllerWithIdentifier ("three") as UIViewController self. navigationController ?. PushViewController (mainVc, animated: true )}

At first glance, I am dizzy again. What are those in the middle .. First, we start fromstoryboardCreate a controller (hand-written, to learn more ).instantiateViewControllerWithIdentifierInthreeSettings

ThenpushGo in. The navigation controller uses the stack method for advanced post-release and push and pop. ThatstoryboardPutLabelAnd oneButtonWill introduce it later. Let's see the effect first.

Then we will register an event for that button, and drag it here.
The implementation is as follows:

 @IBAction func showTabBar(sender: AnyObject) {        let mainVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("second") as! UINavigationController        self.presentViewController(mainVc, animated: true) { () -> Void in        }    }

From herestoryboardLoad the controller but usepresentViewControllerBecause the navigation controller does not allow the push navigation controller.storyboardCreate a navigation Controller

2. Create UINavigationController through storyboard

If you useMain.storyboardYou can delete the default controller and drag it from the rightUINavigationControllerThis will includeUITableViewController, Delete, drag a commonUIViewController. SelectedUINavigationControllerRight-click to dragUIViewControllerSelectrootViewControllerThat's all. Then you can dragBarButtonItemYou can also write it in the code. I dragged in here.

This is the drag-and-drop, because the drag-and-drop will not be involved, and the registration event will also be delayed, just like the button. The demo is no longer displayed.

The running effect at this time.

Here we usepresentViewControllerPop-up responsedismissViewControllerAnimated

@ IBAction func goBack (sender: UIBarButtonItem) {self. dismissViewControllerAnimated (true) {()-> Void in print ("return ")}}

The basic operation of the navigation controller is very simple. The following describes how to download the inverse values on different pages.

3. Several Methods for passing page values
  • Positive and negative value transfer (Protocol)

We can see that three buttons and an input box are put on that page, and all the buttons have registered the event. Then a new controller is written, which contains a return button and severallabelThere is also an input box.

When we click the first button, we enter the next controller. The controller has a method.

func  passParams(tmpStr: String){        lb.text = tmpStr    }

So before pushing, we call this method to pass the value on the front. Of course, you can directly assign values to its common attributes.

let vc = ViewControllerFour()let value = tf1.textvc.passParams(value!)        self.navigationController?.pushViewController(vc, animated: true)

Very simple,lb.text = tmpStrWill assign the passed valuelabel.

A proxy is used for reverse value transfer. First, a protocol is declared.

protocol ParameterDelegate{    func passParams(tmpStr: String)}

Then implement the Protocol on our first page. Implementation Method

    func passParams(tmpStr: String){        tf1.text = tmpStr    }

Then declare the proxy as your own variable on the second page.

 var delegate:ParameterDelegate?

Set yourself as the proxy for the second page before pushing

Let vc = ViewControllerFour () vc. delegate = self // use a proxy to reverse pass the value let value = tf1.text vc. passParams (value !) Self. navigationController ?. PushViewController (vc, animated: true)

I have noticed that I have more than one sentence.

OK. See the results!

  • Method 2 (pass the value through segue)

Directly passstoryboardDrag, saystoryboardIt is really convenient to do the interface. You need to study it carefully.

Drag a new controller and connect it. I have dragged it down. I will demonstrate the link.


Then in the code

// Override func prepareForSegue (segue: UIStoryboardSegue, sender: AnyObject ?) {If segue. identifier = "toshow" {let vc = segue. destinationViewController! ViewControllerTwoShow vc. tmpStr = tf1.text // vc. setValue (tf1, forKey: "tmpStr ")}}

Variable defined in the target controllertmpStr(The Code will be shared later)

View the effect

  • Notification
Let vc = ViewControllerFour () vc. delegate = self // use a proxy to reverse pass the value self. presentViewController (vc, animated: true) {()-> Void in // release a notification NSNotificationCenter. defaultCenter (). postNotificationName ("DefaultNotif", object: self. tf1.text )}

Register a notification first, and publish a notification when the display interface is complete. In another interfaceviewWillAppearReceive notifications.

Override func viewWillAppear (animated: Bool) {// self. navigationController ?. HidesBarsOnSwipe = true self. navigationController ?. SetNavigationBarHidden (true, animated: true) // hide NSNotificationCenter. defaultCenter (). addObserver (self, selector: "doSomeT:", name: "DefaultNotif", object: nil )}

Method

func doSomeT(title:NSNotification){        lb1.text = title.object as? String    }

See the results:

So much. I finally sent the source code. The language is not very good and I don't know it clearly. You can refer to the source code. This address will be put in the source code in the future.starOh)
GithubSwiftStudy

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

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.