今天做一个demo的时候,有一个在点击按钮之后改变按钮title并且同步到NSUserDefaults中的需求
if ([sender.titleLabel.text isEqualToString:@"🔁"]) {
[sender setTitle:@"1" forState:UIControlStateNormal];
}
if ([sender.titleLabel.text isEqualToString:@"1"]) {
[sender setTitle:@"🔀" forState:UIControlStateNormal];
}
if ([sender.titleLabel.text isEqualToString:@"🔀"]) {
[sender setTitle:@"🔁" forState:UIControlStateNormal];
}
[[NSUserDefaults standardUserDefaults] setValue:sender.titleLabel.text forKey:@"playModal"];
[[NSUserDefaults standardUserDefaults] synchronize];
执行过后发现,我的同步总是慢一拍.即明明按钮的图标发生变化,但是我同步的数据总是变化前的值.比如由🔀 变化到 🔁 按钮已经发生变化,但是我同步到的是🔀.
这里当然有很多方法去解决,比如currentTitle 比如 TitleForState.但是我好奇的是为什么textLabel不行.
然后我进去看了一下TextLabel的说明
// return title and image views. will always create them if necessary. always returns nil for system buttons
@property(nullable, nonatomic,readonly,strong) UILabel *titleLabel NS_AVAILABLE_IOS(3_0);
//这里说如果是系统按钮,总是返回空.
所以我用button的Custom样式进行测试
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 100, 100);
button.backgroundColor = [UIColor yellowColor];
[button setTitle:@"button" forState:UIControlStateNormal];
[self.view addSubview:button];
[button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)click:(UIButton *)sender{
NSLog(@"%@",sender.titleLabel.text);
if ([sender.titleLabel.text isEqualToString:@"button"]) {
[sender setTitle:@"no" forState:UIControlStateNormal];
}else{
[sender setTitle:@"button" forState:UIControlStateNormal];
}
NSLog(@"%@",sender.titleLabel.text);//结果表明,完成我所需要的需求
}
所以,textLabel并不是不能用来实时获得按钮的title的.
我接着试了其他类型,发现除了system类型以外,其他的类型所返回的textLabel.text都是null.而system类型则出现了我一开始讲的慢一步现象.即不能实时改变,但是下一次点击时发现它的textLabel已经改变.
所以我根据了按钮的点击触发先后顺序进行测试
[button addTarget:self action:@selector(clickD:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(clickU:) forControlEvents:UIControlEventTouchUpInside];
- (void)clickD:(UIButton *)sender{
NSLog(@"%@",sender.titleLabel.text);//打印结果 button
if ([sender.titleLabel.text isEqualToString:@"button"]) {
[sender setTitle:@"no" forState:UIControlStateNormal];
}else{
[sender setTitle:@"button" forState:UIControlStateNormal];
}
NSLog(@"%@",sender.titleLabel.text);//打印结果 button
}
- (void)clickU:(UIButton *)sender{
NSLog(@"%@",sender.titleLabel.text);//打印结果 no
}
所以,最终得出的结论是,在system类型中,一个点击方法完成后才完成修改titleLabel.text的值.
网友评论