Elton's Blog

如何在iPhone编程中使用UITextField

by on 十.06, 2009, under iPhone

下面的例子将展示如何通过UITextField的内容来改变UILabel中的内容

实现UITextField Delegate协议

首先我们需要在viewController的接口中声明实现UITextFieldDelegate代理协议

1
2
3
4
@interface TextField : UIViewController<UITextFieldDelegate> {
 
}
@end

添加UILabel 和 UITextField对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#import "TextField.h"
 
@implementation TextField
UILabel *label;
UITextField *textField;
 
- (void)viewDidLoad {
    [super viewDidLoad];
 
	//Create label
	label = [[UILabel alloc] init];
	label.frame = CGRectMake(10, 10, 300, 40);
	label.textAlignment = UITextAlignmentCenter;
	label.text = @"";
	[self.view addSubview:label]; 
 
	// Initialization code
	textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 50)];
	textField.delegate = self;
	textField.placeholder = @"<Enter Text>";
	textField.textAlignment = UITextAlignmentCenter;
	[self.view addSubview: textField];
}
 
- (void)dealloc {
	[textField release];
	[label release];
    [super dealloc];
}
 
@end

这段程序没有什么好说的,就是建立并初始化一个UILabel和UITextField对象

实现代理方法

1
2
3
4
5
6
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
	label.text = textField.text;
	[textField resignFirstResponder];
 
    return YES;
}

当用户按了键盘上的Return键后,此方法被调用。 它做了两件事,一件是把UILabel中的值设置成UITextField中的值,另外一个是关闭虚拟键盘。

iPhone编程中大量使用了代理和回调方法,是一种基本的设计模式,所以大家要熟悉这种编程模式。





:, ,

3 Comments for this entry

  • nil

    我没有进行UITextFieldDelegate声明,textFieldShouldReturn依旧被执行到.
    另外,很多地方interface builder可以搞定,用代码莫非更易于维护? 好像不是吧 :)
    你的很多文章写的不错,对我很有用,谢谢.

    • Elton

      我并不是排斥interface builder,不过我觉得作为初学者,最好还是以代码方式来学,比较有条理,所有逻辑都集中在代码上,而不是一会打开interface builder一会再看xcode。

      我觉得如果熟悉后,代码结合interface builder比较好,即有比较高的效率,又能充分控制程序。

      谢谢你的支持。

  • youminbuluo

    我感觉代码懂了就不用理会那个该死的interface builder了,呵呵

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit my friends!

A few highly recommended friends...