First iOS App_Implementing the View Controller

完成/实现视图控制器Implementing the View Controller

实现视图控制器分为以下几部分:为用户名字符串标签添加一个属性;完成 changeGreeting:方法;确保用户点击输入键盘的 完成(Done)按钮时,键盘解除。There are several parts to implementing the view controller: You need to add a property for the user’s name, implement the changeGreeting: method, and ensure that the keyboard is dismissed when the user taps Done.

 

为用户名添加一个属性Add a Property for the User’s Name

为用户名字符串添加一个属性声明,这样你的视图控制器类的会有一个用户名引用的代码。因为这个属性应该是公共的(@public),就表示对用户和控制器的子类是可以访问的,会添加到视图控制器的头文件 HelloWorldViewController.h 中。公共的属性表明你打算如何调用类对对象。You need to add a property declaration for the string that holds the user’s name, so that your code always has a reference to it. Because this property should be public—that is, visible to clients and subclasses—you add this declaration to the view controller’s header file, HelloWorldViewController.h. Public properties indicate how you intend objects of your class to be used.

属性声明是一个指令,告诉编译器如何为一个可变元素,比如可变的用户名,生成访问器。(添加了属性声明后,你会学到访问器方法。)A property declaration is a directive that tells the compiler how to generate the accessor methods for a variable, such as the variable used to hold the user’s name. (You’ll learn about accessor methods after you add the property declaration.)

指导中的这个点,你不需要对 storyboard文件做更多改变。要给自己多留些空间写代码,就点击工具区按钮(或者菜单栏中选择视图>实用工具>隐藏实用工具),把实用工具区关掉。At this point in the tutorial, you don’t need to make any further changes to the storyboard file. To give yourself more room in which to add the code described in the following steps, hide the utilities area by clicking the Utilities View button again (or by choosing View > Utilities > Hide Utilities).


bullet
To add a property declaration for the user’s name

编译器会自动将你声明的所有访问器方法同步。一个访问器方法(getter/setter)是指获取或者设置对象属性的值。例如,编译器为用户名属性(userName)生成如下 getter/setter 的声明,同时还有他们的实现:The compiler automatically synthesizes accessor methods for any property you declare. An accessor method is a method that gets or sets the value of an object’s property (sometimes, accessor methods are also called “getters” and “setters”). For example, the compiler generates declarations of the following getter and setter for the userName property you just declared, along with their implementations:

  • - (NSString *)userName;

  • - (void)setUserName:(NSString *)newUserName;

编译器也会自动为声明是私有的(@private)变量,支持每一个声明的属性。例如,声明一个名为_userName的实例化变量,支持 userName 属性。The compiler also automatically declares private instance variables to back each declared property. For example, it declares an instance variable named _userName that backs the userName property.


Note: 编译器添加访问器方法,生成对应的编译好的代码;不需要在源文件中添加代码。The compiler adds the accessor methods that it generates to the compiled code; it does not add them to your source code.

 

完成 changeGreeting: 方法Implement the changeGreeting: Method

在前面的章节,“配置视图”中,已经对 hello按钮进行了配置,当用户点击按钮,发送一个 changeGreeting: 消息到视图控制器。在响应时,希望视图控制器在标签中显示用户输入到文本区的文字。特别提示, changeGreeting: 方法应该是:In the previous chapter, “Configuring the View,” you configured the Hello button so that when the user taps it, it sends a changeGreeting: message to the view controller. In response, you want the view controller to display in the label the text that the user entered in the text field. Specifically, the changeGreeting: method should:

  • 检索文本区的字符串,视图控制器的 userName属性设置成这个字符串。Retrieve the string from the text field and set the view controller’s userName property to this string.

  • 基于用户名属性(userName)创建一个新的字符串,并显示在标签中。Create a new string that is based on the userName property and display it in the label.


bullet
To implement the changeGreeting: method

在 changeGreeting: 方法中的一些需要注意的有趣的点:There are several interesting things to note in the changeGreeting: method:

  • self.userName = self.textField.text; 检索文本区的文本,把结果设置到视图控制器的 userName 属性中。retrieves the text from the text field and sets the view controller’s userName property to the result.

    在本次指导中,你不需要用到用户名字符串,但是,记录它的角色是很重要的:这是视图控制器正在管理的简单模型对象。一般情况下,控制器应该维持应用程序数据信息在它自己的模型对象——应用数据不应该被存储到用户接口元素比如 HelloWorld应用的文本区中。In this tutorial, you don’t actually use the string that holds the user’s name anywhere else, but it’s important to remember its role: It’s the very simple model object that the view controller is managing. In general, the controller should maintain information about app data in its own model objects—app data shouldn’t be stored in user interface elements such as the text field of the HelloWorld app.

  • NSString *nameString = self.userName; 创建一个新变量(NSStirng类型的变量),设置给视图控制器的 userName 属性。creates a new variable (of type NSString) and sets it to the view controller’s userName property.

  • "World"是一个不变的字符串,代表一个 NSString 类型的实例。如果用户运行应用,但不输入任何文本,nameString 的内容会是"World"。@"World" is a string constant represented by an instance of NSString. If the user runs your app but does not enter any text (that is, [nameString length] == 0), nameString will contain the string “World”.

  • initWithFormat: 方法是由 Foundation.framework 框架提供的。这个静态/类方法会创建一个新的字符串,格式是你提供的字符串格式(特别类似 C语言函数库中的 printf函数)。The initWithFormat: method is supplied for you by the Foundation framework. It creates a new string that follows the format specified by the format string you supply (much like the printf function of the ANSI C library).

    在你提供的格式字符串,%@扮演一个字符串对象的占位。格式字符串中所有其他双引号中的字符都会显示它们引号中的样子。In the format string, %@ acts as a placeholder for a string object. All other characters within the double quotation marks of this format string will be displayed onscreen exactly as they appear.

 

配置视图控制器作为文本区的代理Configure the View Controller as the Text Field’s Delegate

如果你编译并运行应用,你应该会发现,当你点击按钮时,标签显示“Hello,World!”。如果你选择文本区,开始在键盘输入,然而,你应该发现,当你完成输入时,还是没有办法解除键盘。If you build and run the app, you should find that when you click the button, the label shows “Hello, World!” If you select the text field and start typing on the keyboard, though, you should find that you still have no way to dismiss the keyboard when you’re finished entering text.

在一个iOS应用中,当一个元素允许文本输入变成第一响应者时,键盘是自动显示的;在元素解除第一响应者状态时,键盘又自动解除。(重新调用第一响应者时第一个回应各种事物通知的对象,例如点击文本区会弹出键盘。)虽然没有办法从你的应用直接发送消息到键盘,你可以让键盘出现、消失,作为切换文本输入的UI元素的第一响应者状态切换。In an iOS app, the keyboard is shown automatically when an element that allows text entry becomes the first responder; it is dismissed automatically when the element loses first responder status. (Recall that the first responder is the object that first receives notice of various events, such as tapping a text field to bring up the keyboard.) Although there’s no way to directly send a message to the keyboard from your app, you can make it appear or disappear as a side effect of toggling the first responder status of a text-entry UI element.

UITextFieldDelegate协议是UIKit框架定义的,这个协议包括 textFieldShouldReturn:方法,文本区会在用户点击返回按钮(作为按钮的实际标题)时调用这个方法。因为你是指了视图控制器作为文本区的代理(在“To set the text field’s delegate”),你可以通过发送resignFirstResponder消息(有可以解除键盘的副作用),完成这个方法来强制文本区取消第一响应者的状态。The UITextFieldDelegate protocol is defined by the UIKit framework, and it includes the textFieldShouldReturn: method that the text field calls when the user taps the Return button (regardless of the actual title of this button). Because you set the view controller as the text field’s delegate (in “To set the text field’s delegate”), you can implement this method to force the text field to lose first responder status by sending it the resignFirstResponder message—which has the side effect of dismissing the keyboard.


Note: 一个基于一系列方法的协议。如果一个类符合(或者采用)这个协议,它确保会实现@required标志的协议方法。(协议还包括@optional方法)。一个代理协议指定一个对象可能会发送给它的代理的所有消息。A protocol is basically just a list of methods. If a class conforms to (or adopts) a protocol, it guarantees that it implements the required methods of a protocol. (Protocols can also include optional methods.) A delegate protocol specifies all the messages an object might send to its delegate.


bullet
To configure HelloWorldViewController as the text field’s delegate
  1. 如果需要,在项目导航中选择 HelloWorldViewController.m If necessary, select HelloWorldViewController.m in the project navigator.

  2. 在 HelloWorldViewController.m实现 textFieldShouldReturn:方法。这个方法应该告诉文本区,以注销第一响应者状态。它的实现代码如下:Implement the textFieldShouldReturn: method in the HelloWorldViewController.m file.The method should tell the text field to resign first responder status. The implementation should look something like this:

    - (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
        if (theTextField == self.textField) {
            [theTextField resignFirstResponder];
        }
        return YES;
    }

    在这个应用中,确实不需要测试 theTextField == self.textField 表达,因为不止一个文本区需要解除键盘。这是一个好用的设计模式,然而,因为当你的对象不仅仅是同种类型的对象的代理,你需要区别这些对象。In this app, it’s not really necessary to test the theTextField == self.textField expression because there’s only one text field. This is a good pattern to use, though, because there may be occasions when your object is the delegate of more than one object of the same type and you might need to differentiate between them.

  3. 在项目导航中选择 HelloWorldViewController.hSelect HelloWorldViewController.h in the project navigator.

  4. 在头文件声明行(@interface行)的最后添加<UITextFieldDelegate>,你的头文件声明应该如下:To the end of the @interface line, add <UITextFieldDelegate>.

    Your interface declaration should look like this:

    @interface HelloWorldViewController : UIViewController <UITextFieldDelegate>
    ...

    这个声明指定,你的 HelloWorldViewController 类采用 UITextFieldDelegate 协议。This declaration specifies that your HelloWorldViewController class adopts the UITextFieldDelegate protocol.

 

 

 

 

 

测试应用Test the App

编译并运行程序。这一次,每个流程应该如你期望的进行。在模拟器,输入用户名后,点击完成按钮解除键盘,然后点击 hello按钮,标签中显示“Hello, Your Name!”。Build and run the app. This time, everything should behave as you expect. In Simulator, click Done to dismiss the keyboard after you have entered your name, and then click the Hello button to display “Hello, Your Name!” in the label.

如果应用没有如期运行,你需要排查故障。对于一些区域(即模块功能)进行调查,查看“故障排查和审查代码”。If the app doesn’t behave as you expect, you need to troubleshoot. For some areas to investigate, see “Troubleshooting and Reviewing Code”.

 

扼要重述Recap

现在,完成视图控制器已经结束了,你已经完成了自己的第一个 iOS应用。恭喜!Now that you’ve finished the implementation of the view controller, you’ve completed your first iOS app. Congratulations!

返回到 今天开始开发iOS应用(Start Developing iOS Apps Today)。如果你的应用不能正常运行,在返回 今天开发iOS应用前 ,看一下下一张的问题-解决方法描述。Return to Start Developing iOS Apps Today to continue learning about iOS app development. If you had trouble getting your app to work correctly, try the problem-solving approaches described in the next chapter before returning to Start Developing iOS Apps Today.

posted @ 2013-10-11 00:01  small英  阅读(116)  评论(0编辑  收藏  举报