经常会遇到图片样式按钮需要进行切换状态的操作(例如:播放器的开始和暂停),若文字的按钮可以通过按钮的 textLable.text 方式来进行区分,那么图片按钮如何通过单一事件控制多种状态,可以尝试如下方式;
首先,正常搭建一个按钮并对其设置 AccessibilityIdentifier 属性标识符;
- (UIButton *)btnPlay {
if (!_btnPlay) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[[UIImage imageNamed:@"Adio_Player_light"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
forState:UIControlStateNormal];
[btn.imageView setAccessibilityIdentifier:@"play"]; // 通过 AccessibilityIdentifier 属性对其设置初始标识符
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
_btnPlay = btn;
}
return _btnPlay;
}
其次,在点击事件中继续根据事件触发的不同状态依次设置对应的 AccessibilityIdentifier 即可;
#pragma mark - Event
- (void)btnClick:(UIButton *)btn {
NSLog(@"%@", [btn.imageView accessibilityIdentifier]);
// NSString *btnTit = [NSString stringWithFormat:@"%@", btn.titleLabel.text];
NSString *btnIdentifier = [NSString stringWithFormat:@"%@", [btn.imageView accessibilityIdentifier]];
if ([btnIdentifier isEqualToString:@"play"]) {
[_player play];
// [btn setTitle:@"暂停" forState:UIControlStateNormal];
[btn setImage:[[UIImage imageNamed:@"Adio_Pause_light"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
[btn.imageView setAccessibilityIdentifier:@"pause"];
} else {
[_player pause];
// [btn setTitle:@"播放" forState:UIControlStateNormal];
[btn setImage:[[UIImage imageNamed:@"Adio_Player_light"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
[btn.imageView setAccessibilityIdentifier:@"play"];
}
}
最后,以上例子是以播放器播放状态为例,实际具体业务还需具体分析,以上方法可供大家参考借鉴。
以上便是此次分享的全部内容,希望能对大家有所帮助!