ios 文本框变化 监听的3种方式
声明属性
@interface LoginControler()
@property (weak, nonatomic) IBOutlet UITextField *userName;
@end
1,代理方式
-(void) viewDidLoad
{
_userName.delegate = self; //添加代理
}
-(BOOL)textField:(UITextField )textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString )string
{
NSLog(@”%@”, textField.text);
return true; //如果NO就不会显示
}
2,通知
这种方式在通知完后还需要释放,麻烦,用的少
-(void) viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:nil];
//addObserver:self 监听者对象
//name 监听的改变对象的方法
//object 监听的对象 nil 全部监听
}
-(void)textChange
{
NSLog(@”%@”, _userName.text);
}
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self]; //移除监听
}
3,动态添加执行方法
-(void) viewDidLoad
{
[_userName addTarget:self action:@selector(textChange) forControlEvents:UIControlEventEditingChanged];
//forControlEvents 触发事件
}
-(void)textChange
{
NSLog(@”%@”, _userName.text);
}
switch 开关的方法
- (IBAction)loginSwith:(UISwitch *)sender
{
if (sender.isOn ) {
[_Test setOn:YES animated:YES];
NSLog(@”开”);
} else {
[_Test setOn:NO animated:YES];
NSLog(@”关”);
}
}
//UIActionSheet 底部弹出提示框
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@”取消” destructiveButtonTitle:@”拍照”otherButtonTitles:@”照相”,nil];
[sheet showInView:self.view];
//initWithTitle 提示栏
//delegate 代理者
//cancelButtonTitle 取消按钮
//destructiveButtonTitle 从上往下的第一个按钮
//otherButtonTitles 第二个按钮
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
NSLog(@"%ld",buttonIndex);
}
//UIAlertView 提示框
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@”标题” message:@”内容” delegate:self cancelButtonTitle:@”取消” otherButtonTitles:@”确定”, nil];
[alert show];
//board 跳转方法
//获取storyboard
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@”Main” bundle:nil];
//获取想要的viewControl
UIViewController *control = [storyboard instantiateViewControllerWithIdentifier:@”phoneStoryboard”];
//push 跳转
[[self navigationController]pushViewController:control animated:YES];
2,
[self performSegueWithIdentifier:@”phonesugue” sender:nil];
//performSegueWithIdentifier 为连接跳转sugue的id
本文介绍了iOS中实现文本框变化监听的三种方法:代理方式、通知方式及动态添加执行方法,并给出了具体的代码实现。
7479

被折叠的 条评论
为什么被折叠?



