Bob*_*Bob 21 xcode uibutton ios
我有一个创建自定义UIButton的方法,允许我使用QuartzCore更改按钮的颜色.但触摸时按钮不会突出显示.
- (UIButton *)makeHeaderButton {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIFont *textFont = [UIFont boldSystemFontOfSize:12];
UIColor *textColor = [UIColor colorWithRed:80/255.0 green:109/255.0 blue:145/255.0 alpha:1.0];
UIColor *backgroundColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1.0];
[button setTitleColor:textColor forState:UIControlStateNormal];
button.titleLabel.font = textFont;
button.autoresizesSubviews = YES;
button.layer.cornerRadius = 8;
button.layer.borderWidth = 1;
// next 2 properties set using QuartzCore class, no other way to set button colors
button.layer.borderColor = [UIColor grayColor].CGColor;
button.layer.backgroundColor = backgroundColor.CGColor;
button.clipsToBounds = YES;
return button;
}
Run Code Online (Sandbox Code Playgroud)
如何使这些按钮突出显示为常规圆形矩形按钮?
Gri*_*ear 17
在Swift中,您还可以覆盖isHighlightedvar并在其上添加alpha动画.
override var isHighlighted: Bool {
didSet {
UIView.animate(withDuration: 0.25, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: {
self.alpha = self.isHighlighted ? 0.5 : 1
}, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
Gar*_*ett 13
在您的代码中,添加该行 button.showsTouchWhenHighlighted = TRUE;
小智 6
对于Swift,创建一个继承UIButton并覆盖isHighlighted属性的自定义类:
class ButtonWithHighlight: UIButton {
override var isHighlighted: Bool {
get {
return super.isHighlighted
}
set {
if newValue {
backgroundColor = <#color when highlighted#>
}
else {
backgroundColor = <#color for normal state#>
}
super.isHighlighted = newValue
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人仍遇到问题 - 您应该像这样创建UIButton:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
btn.layer.cornerRadius = 4;
btn.layer.masksToBounds = YES;
[btn setTranslatesAutoresizingMaskIntoConstraints:NO];
[btn setBackgroundColor:[UIColor greenColor]];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn setTitle:@"ok" forState:UIControlStateNormal];
*** any customisation that you would like ***
[parentView addSubview: btn];
Run Code Online (Sandbox Code Playgroud)
所以这样你仍然可以让iOS处理所有突出显示.主要是使用
[UIButton buttonWithType:UIButtonTypeSystem];
Run Code Online (Sandbox Code Playgroud)
如果您使用initWithFrame或任何其他方法 - 您必须实现
setTitleColor: forState:
setBackgroundImage: forState:
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22442 次 |
| 最近记录: |