iOS programming Delegation and Text Input,iosdelegation

來源:互聯網
上載者:User

iOS programming Delegation and Text Input,iosdelegation

iOS programming Delegation and Text Input 

1.1 Text Fields 

 

CGRect textFieldRect = CGRectMake(40, 70, 240, 30);
UITextField *textField = [[UITextField alloc] initWithFrame:textFieldRect];

// Setting the border style on the text field will allow us to see it more easily textField.borderStyle = UITextBorderStyleRoundedRect;
[backgroundView addSubview:textField];

 

Tap on the text field, and the keyboard will slide up from the bottom of the screen, allowing you to input text. To understand how this is happening under the hood, you need to understand the first responder.

當你點擊text field 時,這個keyboard 將會從螢幕的底部滑上來。要明白在底層發生了什麼,你必須明白first responder.

1.2 UIResponder

UIResponder is an abstract class in the UIKit framework. It is the superclass of three classes that you have already encountered:

    UIView

    UIViewController

    UIApplication

UIResponder 是UIKit 架構的一個抽象類別。他是以下你看到過的三個類的超類。

    UIView

    UIViewController

    UIApplication

UIResponder defines methods for handling (or "responding to") events: touch events, motion events (like a shake), and remote control events (like pausing or playing).

UIResponder定義了處理 事件,觸摸事件,運動事件和遠端控制事件的方法。

Subclasses override these methods to customize how they respond to events.

子類重載這些方法來適應他們如何響應事件。

With touch events, it is obvious which view the user has touched. Touch events are sent directly to that view.

觸摸事件,很明顯使用者觸摸了哪個事件。觸摸事件之間送到那個view。

The UIWindow has a pointer called firstResponder which indicates who should respond to the other types of events.

UIWindow 有一個叫做firstResponse的指標。它指向那個誰應該響應其他類型的事件。

When you select a text field, for example, the window moves its firstResponder pointer to that text field.

如果你選擇 text field ,window 將把fristResponse 指向text field。

When a text field or a text view becomes firstResponder, it shows its keyboard. When it loses first responder status, it hides its keyboard.

當一個text field 或text view 成為firstResponse,它將顯示鍵盤。當它不是firstResponse,它將隱藏鍵盤。

If you want one of these views to become first responder, you send it the message becomeFirstResponder and the keyboard appears. When you want to hide the keyboard, you send it the message resignFirstResponder.

如果你想讓這些視圖的一個成為first responder ,你應該發送becomeFirstResponder 的訊息,鍵盤就出現了。 當你想隱藏keyboard,你向它發送resignFirstResponder訊息。

Most views refuse to become first responder;

很多視圖不想成為first responder.

1.3 Configuring the keyword 

 

textField.placeholder = @"Hypnotize me";
textField.returnKeyType = UIReturnKeyDone;

the return key now says Done instead of the default Return.

 

In fact, the return key does not do anything automatically; you have to implement the return key functionality yourself.

return key 並沒有自動的做某事。你必須實現 返回鍵函數。

 

some of the other useful properties that you can use to configure the keyboard.

下面是一些有關配置keyboard 的屬性。

autocapitalizationType

This determines how capitalization is handled. The options are none, words, sentences, or all characters.

這個決定大寫字母如何處理。選項是無,字,句子,和所有字元。

autocorrectionType

This will suggest and correct unknown words. This value can be YES or NO. 

這個將會建議和更改未知的詞語。這個值可以設定為YES or NO。

enablesReturnKeyAutomatically

This value can be YES or NO. If set to yes, the return key will be disabled if no text has been typed. As soon as any text is entered, the return key becomes enabled.


keyboardType

This determines the type of keyboard that will be displayed. Some examples are the ASCII keyboard, email address keyboard, number pad, and the URL keyboard.

設定鍵盤是ASCII 還是email鍵盤,數字鍵台還是URL鍵盤。
secureTextEntry

Setting this to YES makes the text field behave like a password field, hiding the text that is entered.

設定為密碼形式的輸入

1.4 Delegation 

This is one form of callbacks that is used by UIKit: When a button is tapped, it sends its action message to its target. This typically triggers code that you have written.

當一個button 按下後,它發送一個action 訊息給目標。這觸發了你寫過的代買。

 

You introduce the text field to one of your objects: "This is your delegate, when anything interesting happens in your life, send a message to him."

你把text field 引入你的一個對象: 這是你的委託,當任何感興趣的事情在你的生命週期發生時,給她發送一個訊息。

The text field keeps a pointer to its delegate.

text field 有一個指標指向它的委託。

Many of the message it sends to its delegates are informative: "OK, I am done editing!".

許多發給他的delegate的訊息是:好,我已經完成編輯。

- (void)textFieldDidEndEditing:(UITextField *)textField;
- (void)textFieldDidBeginEditing:(UITextField *)textField;

Notice that it always sends itself as the first argument to the delegate method.

注意:它總是把自己作為第一個參數 傳遞給它的委託方法。

 

Some of the message it sends to its delegate are queries: "I am about to end editing and hide the keyboard. OK?"

一些傳遞給它的委託有關詢問的訊息:我將要結束編輯和隱藏鍵盤。可以嗎

 

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField; - (BOOL)textFieldShouldClear:(UITextField *)textField;
- (BOOL)textFieldShouldReturn:(UITextField *)textField;

 

 

textField.delegate = self;

 

- (BOOL)textFieldShouldReturn:(UITextField *)textField

{
NSLog(@"%@", textField.text);

return YES; }

1.5 protocol 

Before sending an optional message, the object first asks its delegate if it is okay to send that message by sending another message, respondsToSelector:.

當發送一個可選擇的資訊時,object 將通過responseToSelector:詢問它的delegate ,看看object向它的delegate是否可以。

 

- (void)clearButtonTapped

{
// textFieldShouldClear: is an optional method,
// so we check first
SEL clearSelector = @selector(textFieldShouldClear:);

if ([self.delegate respondsToSelector:clearSelector]) { if ([self.delegate textFieldShouldClear:self]) {

self.text = @""; }

} }

If a method in a protocol is required, then the message will be sent without checking first. This means that if the delegate does not implement that method, an unrecognized selector exception will be thrown, and the application will crash.

如果一個method 在protocol 是必須得,那麼這個訊息不檢查就發送。這也就意味著如果你沒有實現該方法,那麼一個未檢查到selector 異常將會拋出。

This is done either in the class header file or the class extension: the protocols that a class conforms to are added to a commadelimited list inside angled brackets in the interface declaration.

 

@interface BNRHypnosisViewController () <UITextFieldDelegate> 

@end

The reason for adding it to the class extension rather than the header file is the same reason as always: add to the class extension if the information (conforming to a particular protocol in this case) does not need to be publicly visible, and add it to the header file if other objects do need to know about the information.

既可以把protocol 添加到class extension 也可以添加到interface 中。

Many classes have a delegate pointer, and it is nearly always a weak reference to prevent strong reference cycles.

許多類都有一個delegate pointer,並且他們都是弱引用以組著強引用迴圈。

1.6 Adding the Labels to the Screen

To make things a little interesting, you are going to add instances of UILabel to the screen at random positions.

你將在螢幕的隨機位置添加UILabel。

 

arc4random() %4 will generate 0, 1, 2 or 3.

arc4random()%5 將產生0,1,2,3,4

update the textFieldShouldReturn: method to call this new method, passing in the text field's text, clear the text that the user typed, and then dismiss the keyboard by calling resignFirstResponder.

- (BOOL)textFieldShouldReturn:(UITextField *)textField

{
NSLog(@"%@", textField.text);
[self drawHypnoticMessage:textField.text];

textField.text = @"";
[textField resignFirstResponder];

return YES; }

1.7 Motion Effects  運動效果

accelerometer, magnetometer, and gyroscope – help determine the orientation of the device.

加速器,磁強計,陀螺儀協助我們決定裝置的方向。

When you drive down the road, the signs along the shoulder appear to move much more quickly than trees in the distance.

當你開車在路上,在路旁的圖片要明顯的比遠處的路標移動的快。

Your brain interprets this difference in apparent speed as movement in space. This visual effect is called "parallax".

你的大腦在移動速度夠明顯時解析這種不同。 這個虛擬效果成為parallax(視差)

With iOS 7, you have probably noticed this on the home screen where the icons appear to move relative to the wallpaper when you tilt the device. It is used subtly (and not so subtlety) in various places across the operating system and bundled apps, including the red badges on Home screen icons, the volume changer pop-up, and alert views.

你注意到在home 屏時,當你傾斜螢幕時,表徵圖相對移動。

Applications can access the same technology that powers those effects by using the UIInterpolatingMotionEffect class.

應用程式也可以通過使用UIInterpolatingMotionEffect獲得同樣地技術。

Instances are given an axis (either horizontal or vertical), a key path (which property of the view do you want to impact), and a relative minimum and maximum value (how much the key path is allowed to sway in either direction).

執行個體變數將提供一個座標軸,(水平的或垂直的),一個關鍵路徑(你想影響視圖的那個屬性)和一個相對最小最大值(在任意方向上,最大最小能搖晃的區間)

UIInterpolatingMotionEffect *motionEffect;

motionEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x"

type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; motionEffect.minimumRelativeValue = @(-25);

motionEffect.maximumRelativeValue = @(25); [messageLabel addMotionEffect:motionEffect];

motionEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y"

type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis]; motionEffect.minimumRelativeValue = @(-25);

motionEffect.maximumRelativeValue = @(25);

[messageLabel addMotionEffect:motionEffect];

1.8 Using breakpoints 

This navigator shows a stack trace of where the breakpoint stopped execution

這個導航顯示了breakpoint 停止執行的stack trace .

A stack trace shows you the methods and functions whose frames were in the stack when the application broke.

a stack trace 顯示了一些方法和函數。這些函數和方法指明了那個架構在棧裡,什麼時候應用停止的。

The method where the break occurred is at the top of the stack trace.

在哪裡停止的方法在stack 的最上面。

Select the method at the top of the stack. In the debug area below the editor area, check out the variables view to the left of the console. This area shows the variables within the scope of BNRHypnosisView's initWithFrame: method along with their current values

選擇stack 最上面的方法,在debug area 地區檢查左側的變數。這個地區將展示在initWithFrame的變數的現有值。

 

1.8 main() and UIApplication

Open main.m in the HypnoNerd project navigator. It looks like this:

int main(int argc, char *argv[])

{
@autoreleasepool {

return UIApplicationMain(argc, argv,
nil, NSStringFromClass([BNRAppDelegate class]));

} }

 

The function UIApplicationMain creates an instance of a class called UIApplication.

UIApplicationMain 函數 創辦了一個成為UIApplication 的執行個體。

For every application, there is a single UIApplication instance.

對於每個程式來說只有一個UIApplication .

This object is responsible for maintaining the run loop. Once the application object is created, its run loop essentially becomes an infinite loop: the executing thread will never return to main().

一旦UIApplication建立好,它的 run loop 將變成無限迴圈:執行的線程不會返回到main中。

Another thing the function UIApplicationMain does is create an instance of the class that will serve as the UIApplication's delegate.

UIApplication還建立了作為UIApplication的委託的類的執行個體。

Notice that the final argument to the UIApplicationMain function is an NSString that is the name of the delegate's class. So, this function will create an instance of BNRAppDelegate and set it as the delegate of the UIApplication object.

注意到UIApplicMain 最後的參數是個字串。作為delegate 類的名字。

The first event added to the run loop in every application is a special "kick-off" event that triggers the application to send a message to its delegate. This message is application:didFinishLaunchingWithOptions:.

添加到run loop 的第一個事件是特殊的kick-off 事件。它將觸發application 發送一個訊息給它的代理。這個訊息就是application:didFinishLaunchingWithOptions.

You implemented this method in BNRAppDelegate.m to create the window and the controller objects used in this application.

你在BNRAppDelegate.m中實現這個方法來建立視窗和用在application的controller 對象。

Every iOS application follows this pattern.

每個iOS application 都應用了這個模式。

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.