Home > Web Front-end > HTML Tutorial > Use Swift's protocol syntax to implement value transfer between pages_html/css_WEB-ITnose

Use Swift's protocol syntax to implement value transfer between pages_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:57:03
Original
1101 people have browsed it

With the release of Swift, a new development language, and the official release of Xcode6.0.1, it is imminent to use Swift to write iOS code. After using Objective-C to develop for nearly three years, the author is very familiar with this elegant syntax. I am deeply impressed. Below I will implement a comparative demo of page value transfer. The syntax used is swift. Page value transfer is a required demo in the early stage of learning iOS because it involves a very difficult syntax: protocol and delegation. What is involved here I won’t go into details about Swift syntax and some basic operations. If it’s convenient, you can download the IT Interview Guide APP, which has a detailed introduction to it. Let’s get straight to the point and use code to implement the following functions:

1. Create a Swift project , you can use XIB or pure code, the main pure code here is, you will notice that this strange language does not have the .h file, but uses the .swift file

2 to modify the display name on the mobile phone screen, This is seriously different from XCODE5. I don’t know whether to go back or forward. The author is speechless. Let’s see how to restore it later

3. Basic swift syntax to define: protocol, forward value transfer and reverse transfer Value, that is, callback

4. Simply mention how to change the default XIB to pure code, that is, delete the XIB file

5. The function of the page is to enter the student number on the homepage, and then click Register. The registration page is presented modally. At this time, the student number filled in on the previous page is displayed. Then enter the name and click OK. Return to the previous page to display the name

That’s it. Let’s implement it specifically. If Newbies can follow the steps. If you encounter syntax you don’t understand, please search it yourself:


1. Create a project. The overall code structure is as follows:

Stop saying anything and go to the next step

Second, build the home page (HomeViewController.swift) and registration page (RegisterViewController.swift) with pure code

class HomeViewController: UIViewController,RegisterDelegate {        var nameLbl : UILabel!    var numTF : UITextField!        override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view.        self.view.backgroundColor = UIColor.whiteColor()        let titleItem : UINavigationItem = UINavigationItem(title: "首页")        let NVC : UINavigationBar = UINavigationBar(frame: CGRectMake(0, 20, 320, 44))        NVC.setItems([titleItem], animated: true)        self.view.addSubview(NVC)                                numTF = UITextField(frame: CGRectMake(10, 100, 300, 35))        numTF.placeholder = "输入学号"        numTF.borderStyle = UITextBorderStyle.Line        numTF.textAlignment = NSTextAlignment.Center        numTF.clearButtonMode = UITextFieldViewMode.WhileEditing        self.view.addSubview(numTF)                nameLbl = UILabel()        nameLbl.frame = CGRectMake(10, 150, 300, 40)        nameLbl.text = ""        nameLbl.backgroundColor = UIColor.lightGrayColor()        nameLbl.textAlignment = NSTextAlignment.Center        self.view.addSubview(nameLbl)                                let registerBtn : UIButton = UIButton()        registerBtn.frame = CGRectMake(10, 200, 300, 40)        registerBtn.backgroundColor = UIColor.lightGrayColor()        registerBtn.setTitle("注册", forState: UIControlState.Normal)        registerBtn.addTarget(self, action: "registerClick:", forControlEvents: UIControlEvents.TouchUpInside)        self.view.addSubview(registerBtn)            }
Copy after login

Pay attention to the navigation bar code and various UI codes. It is a very strange way of writing. Currently, the author only adapts to 320 and nothing else. You can adapt by yourself. In this way, a homepage UI is created Out, then implement the click event:

 func goRegister(){                if numTF.text.isEmpty {                        var alert : UIAlertView = UIAlertView(title: "不能为空", message: "填写你的学号", delegate: nil, cancelButtonTitle: "知道了")            alert.show()            numTF.becomeFirstResponder()                    }else{                        var rootVC :RegisterViewController = RegisterViewController()            let NVC :UINavigationController = UINavigationController(rootViewController: rootVC)            self.presentViewController(NVC, animated: true, completion: nil)        }            }
Copy after login

This brings you to the registration page (RegisterViewController.swift). Now paste the registration page code:

class RegisterViewController: UIViewController,UITextFieldDelegate{    var nameTF : UITextField!    var num : String!        override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view.                self.view.backgroundColor = UIColor.whiteColor()        self.title = "注册"                let leftItem : UIBarButtonItem? = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "back")        self.navigationItem.leftBarButtonItem = leftItem                        let numLbl : UILabel = UILabel()        numLbl.frame = CGRectMake(10, 100, 300, 40)        numLbl.text = self.num        numLbl.backgroundColor = UIColor.lightGrayColor()        numLbl.textAlignment = NSTextAlignment.Center        self.view.addSubview(numLbl)                       nameTF = UITextField(frame: CGRectMake(10, 150, 300, 35))        nameTF.placeholder = "输入姓名"        nameTF.textAlignment = NSTextAlignment.Center        nameTF.borderStyle = UITextBorderStyle.Line        nameTF.clearButtonMode = UITextFieldViewMode.WhileEditing        nameTF.delegate = self        self.view.addSubview(nameTF)                        var submitBtn : UIButton = UIButton(frame: CGRectMake(10, 210, 300, 40))        submitBtn.backgroundColor = UIColor.lightGrayColor()        submitBtn.setTitle("确定", forState: UIControlState.Normal)        submitBtn.addTarget(self, action: "submitClick:", forControlEvents: UIControlEvents.TouchUpInside)        self.view.addSubview(submitBtn)    }
Copy after login

There is a cancel button here, and the rest is the same as the homepage, to implement the click confirmation code:

 func submitClick(sender : UIButton)    {        goBack()    }        func goBack(){                if nameTF.text.isEmpty {                        var alert : UIAlertView = UIAlertView(title: "不能为空", message: "填写你的名字", delegate: nil, cancelButtonTitle: "知道了")            alert.show()            nameTF.becomeFirstResponder()                    }else{                                    self.dismissViewControllerAnimated(true, completion: { () -> Void in                                                println("我要确定了,你知道吗?");            })        }    }             //MARK: TFDELEGATE        func textFieldShouldReturn(textField: UITextField) -> Bool {                goBack()                return true    }        override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {        self.view.endEditing(true)    }
Copy after login

This code can also be used Note, there is an extra click view to cancel, so the editing response event

can be switched between pages here. The specific code is indeed very different, and the swift syntax and UI syntax are themselves Learn


3. Create a protocol

Write the code in the HomeViewController file as follows:

import UIKitprotocol RegisterDelegate{    func registerName(name : NSString)}class HomeViewController: UIViewController,RegisterDelegate {        var nameLbl : UILabel!    var numTF : UITextField!
Copy after login
........  
Copy after login

Pay attention to implement this protocol, and then implement the protocol as follows:

           func registerName(name: NSString) {        nameLbl.text = name    }    
Copy after login

Friends who know object-C should understand this step very well. Before that, we To implement a protocol object on the delegated page, the code is as follows:

import UIKitclass RegisterViewController: UIViewController,UITextFieldDelegate{    var nameTF : UITextField!    var delegate : RegisterDelegate!    var num : String!        override func viewDidLoad() {        super.viewDidLoad()
Copy after login
.....
Copy after login

Pay attention to the delegate here. This is the protocol delegation object. To put it bluntly, You need to pass the value of the previous home page object to the delegate, and the delegate follows the protocol, so when the delegate calls a method in the protocol, the implementation process of this method will be executed by home in the home page. This can achieve The value of the registration page is transferred to the home page for display. This is the benefit of using protocols and delegation together. Okay, if you are confused when you see this, please put it down and read it. Don’t worry about this sentence for now. Let’s go back to home to see how to set up the proxy. The code is as follows. By the way, take a look at the code I am using to transfer the student ID to the registration page:

 func goRegister(){                if numTF.text.isEmpty {                        var alert : UIAlertView = UIAlertView(title: "不能为空", message: "填写你的学号", delegate: nil, cancelButtonTitle: "知道了")            alert.show()            numTF.becomeFirstResponder()                    }else{                        var rootVC :RegisterViewController = RegisterViewController()            rootVC.delegate = self;            rootVC.num = self.numTF.text                        let NVC :UINavigationController = UINavigationController(rootViewController: rootVC)                        self.presentViewController(NVC, animated: true, completion: nil)        }            }
Copy after login

Then we will go back Go to the registration page to see where the delegate calls the protocol method:

   func goBack(){                if nameTF.text.isEmpty {                        var alert : UIAlertView = UIAlertView(title: "不能为空", message: "填写你的名字", delegate: nil, cancelButtonTitle: "知道了")            alert.show()            nameTF.becomeFirstResponder()                    }else{                        self.delegate!.registerName(self.nameTF.text)                        self.dismissViewControllerAnimated(true, completion: { () -> Void in                                                println("我要确定了,你知道吗?");            })        }    }
Copy after login


Pay attention to the differences Ah, if it is not empty, the name is passed to the parameters of the protocol method and brought to the homepage for display, thus realizing a callback value-passing function.


If you complete the previous steps, you can test whether you can transfer values ​​​​to each other. If it succeeds, you can take a rest. Let’s briefly mention the contents of AppDelegate.swift How did I write it? Note that I deleted the default ViewController.swift after it was created

    var window: UIWindow?    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {        // Override point for customization after application launch.                self.window?.rootViewController = HomeViewController()                        return true    }
Copy after login

The fourth step is to replace the Main.storyboard file with pure code. First Delete Main.storyboard

The code is as follows:

var window: UIWindow?    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {        // Override point for customization after application launch.                        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)        self.window?.backgroundColor = UIColor.whiteColor()        self.window?.makeKeyAndVisible()        self.window?.rootViewController = HomeViewController()                        return true    }
Copy after login

This is equivalent to pure code to implement all the code

Fifth Step, modify the display name

Since Xcode6 does not have the InfoPlist.strings file, you need to create a file with the same name, and because the key: Bundle display name is missing in the info file, you need to add it manually, and then Write the same code as Xcode5 in the InfoPlist.strings file:

"CFBundleDisplayName" = "学号注册";
Copy after login

至此我们就实现了最初设定的全部功能,可以说这也是笔者的一次摸索,如此简单的一个demo却耗费了半天的时间,其中不乏对语法的查阅,功能的查找,确实来之不易,希望给读者带来效率,如需代码,加下面QQ群可索取,实现效果图:


附录:转载本博客,请注明出处,维护版权,人人有责。



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template