http://www.devdiv.com/storyboard_first_responder_-blog-1-50012.html
相信很多开发者看到storyboard中的这个first responder都会有这样的疑问:这个东东是做什么的?
原理讲解:
本文着重给大家讲讲什么是First Responder,我们将通过一个例子讲解它的使用,具体如下:
1. 创建Single View Application工程,命名为:FirstResponderTest
2. 在Storyboard中添加两个Text Field,两个Button
3. 为Paste按钮设置Touch Down event,指向First Responder
在弹出菜单中选择Paste
我们希望在我们点击Paste button时候执行First Responder的paste: action。
4. 接下来在ViewController.h中添加两个Text Field outlet,具体如下:
然后按照下图填写
5. 在ViewController.m中添加以下代码:
[代码]c#/cpp/oc代码:
1 | @synthesize textField1; |
2 | @synthesize textField2; |
[代码]c#/cpp/oc代码:
01 | NSString *copyString = @"Hello DevDiv!" ; |
02 |
03 | UIPasteboard *pb = [UIPasteboard generalPasteboard]; |
04 |
05 | [pb setString:copyString]; |
06 |
07 |
08 |
09 | // Set first responder |
10 |
11 | [textField1 becomeFirstResponder]; |
这是因为:
1). Paste button的touch down event调用First Responder的paste: action,
2). 而此时textField1是First Responder,
3). 所以Paste button实际上调用的是textField1的paste: action。
8. 接下来我们为Switch FR button添加touch down event处理,具体代码如下:
[代码]c#/cpp/oc代码:
1 | - (IBAction)switchFR:(id)sender { |
2 | if ([textField1 isFirstResponder]){ |
3 | [textField2 becomeFirstResponder]; |
4 | } |
5 | else { |
6 | [textField1 becomeFirstResponder]; |
代码并不复杂,让两个Text Field轮流担任First Responder。
9. 我们再执行程序,切换First Responder如果这是点击Paste按钮,那么你会发现,字符串被Copy到不同的Text Field。
总结如下:
1. Storyboard中的First Responder只是一个placeholder,它不是具体指向哪个responder,
2. 如果程序不在乎谁是First Responder,都让First Responder执行某个action(比如这里的paste:),那么我们就可以把event发给First Responder。