


Use Swift's protocol syntax to implement value transfer between pages_html/css_WEB-ITnose
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) }
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) } }
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) }
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) }
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!
........
Pay attention to implement this protocol, and then implement the protocol as follows:
func registerName(name: NSString) { nameLbl.text = name }
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()
.....
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) } }
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("我要确定了,你知道吗?"); }) } }
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 }
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 }
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" = "学号注册";
至此我们就实现了最初设定的全部功能,可以说这也是笔者的一次摸索,如此简单的一个demo却耗费了半天的时间,其中不乏对语法的查阅,功能的查找,确实来之不易,希望给读者带来效率,如需代码,加下面QQ群可索取,实现效果图:
附录:转载本博客,请注明出处,维护版权,人人有责。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

Title: Implementation method of page jump in 3 seconds: PHP Programming Guide In web development, page jump is a common operation. Generally, we use meta tags in HTML or JavaScript methods to jump to pages. However, in some specific cases, we need to perform page jumps on the server side. This article will introduce how to use PHP programming to implement a function that automatically jumps to a specified page within 3 seconds, and will also give specific code examples. The basic principle of page jump using PHP. PHP is a kind of

"Methods to handle Laravel pages that cannot display CSS correctly, need specific code examples" When using the Laravel framework to develop web applications, sometimes you will encounter the problem that the page cannot display CSS styles correctly, which may cause the page to render abnormal styles. Affect user experience. This article will introduce some methods to deal with the failure of Laravel pages to display CSS correctly, and provide specific code examples to help developers solve this common problem. 1. Check the file path. First check the path of the CSS file.

PHP is a server-side scripting language widely used in web development. Its main function is to generate dynamic web content. When combined with HTML, it can create rich and colorful web pages. PHP is powerful. It can perform various database operations, file operations, form processing and other tasks, providing powerful interactivity and functionality for websites. In the following articles, we will further explore the role and functions of PHP, with detailed code examples. First, let’s take a look at a common use of PHP: dynamic web page generation: P
