我有以下UIButton:
// create footerView
let footerView: UIView = UIView()
footerView.backgroundColor = UIColor.yellowColor()
self.view.addSubview(footerView)
footerView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(self.view.snp_left)
make.right.equalTo(self.view.snp_right)
make.height.equalTo(self.footerHeight)
make.bottom.equalTo(self.view.snp_bottom)
}
let footerButton: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
footerButton.setTitle("OK", forState: UIControlState.Normal)
footerButton.backgroundColor = UIColor.redColor()
footerButton.tintColor = UIColor.whiteColor()
footerButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted)
footerView.addSubview(footerButton)
footerButton.snp_makeConstraints { (make) -> Void in
make.center.equalTo(footerView)
make.left.equalTo(footerView.snp_left).offset(45)
make.right.equalTo(footerView.snp_right).offset(-45)
}
编辑:我可以使用
footerButton.setBackgroundImage(redImage, forState: UIControlState.Highlighted)
但如果我按下按钮,这会破坏自动布局和边框半径。
如何更改UIControlState.Highlighted
上按钮的backgroundColor?
答案 0 :(得分:1)
没有-setBackgroundColor:forState
方法。您可以创建纯色背景图像(以编程方式或包含在资源中),然后使用
- setBackgroundImage:forState:
答案 1 :(得分:0)
@ stephan1001我已经尝试过这段代码并且可以正常使用
class ViewController: UIViewController {
var footerHeight = 70.0
override func viewDidLoad() {
super.viewDidLoad()
configUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func configUI(){
// create footerView
let footerView: UIView = UIView()
footerView.backgroundColor = UIColor.yellowColor()
self.view.addSubview(footerView)
footerView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(self.view.snp_left)
make.right.equalTo(self.view.snp_right)
make.height.equalTo(self.footerHeight)
make.bottom.equalTo(self.view.snp_bottom)
}
let footerButton: MyButton = MyButton.buttonWithType(UIButtonType.Custom) as! MyButton
footerButton.setTitle("OK", forState: UIControlState.Normal)
footerButton.backgroundColor = UIColor.redColor()
footerButton.tintColor = UIColor.whiteColor()
footerButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted)
footerView.addSubview(footerButton)
footerButton.snp_makeConstraints { (make) -> Void in
make.center.equalTo(footerView)
make.left.equalTo(footerView.snp_left).offset(45)
make.right.equalTo(footerView.snp_right).offset(-45)
}
}
}
class MyButton: UIButton{
override var highlighted: Bool {
willSet(newValue) {
if ( newValue == true ){
self.backgroundColor = UIColor.greenColor()
} else{
self.backgroundColor = UIColor.redColor()
}
}
}
}