我在 Swift 4 中编写了一个函数,它创建了一个按钮,该按钮接收 UIButton
、一个颜色和一个字符串作为标题。我想为此功能添加一个突出显示或点按样式,但我不确定如何操作。
函数:
func homeBtn(button: UIButton, color: UIColor, title: String){
button.setTitle(title, for: .normal)
button.setTitleColor(color, for: .normal)
button.titleLabel?.font = UIFont(name: "Raleway-Medium", size: 24)
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.titleEdgeInsets = UIEdgeInsetsMake(20,20,20,20)
button.layer.borderColor = color.cgColor
button.layer.borderWidth = 2
button.layer.cornerRadius = button.frame.width/2
button.layer.backgroundColor = whiteColor.cgColor
}
按钮是一个圆圈,中间有一个字符串,UIColor
用作轮廓。有人可以告诉我如何向使用相同 UIColor
填充按钮并将文本变为白色的此功能添加点击样式吗?
最佳答案
对于标题颜色,您无需添加事件即可轻松做到这一点。
button.setTitleColor(.white, for: .highlighted)
button.setTitleColor(.black, for: .normal)
对于背景颜色,您需要定义以下事件:
button.addTarget(self, action: #selector(touchDown(button:)), for: .touchDown)
button.addTarget(self, action: #selector(touchUpInside(button:)), for: .touchUpInside)
定义函数 - 您也可以引用其他触摸类型 - 请参阅 UIControlEvents
@objc func touchDown(button: UIButton) {
guard let borderColor = button.layer.borderColor else {
return
}
button.backgroundColor = UIColor(cgColor: borderColor)
}
@objc func touchUpInside(button: UIButton) {
// Set backgroundColor for normal state...
}
关于ios - UIButton 函数添加点击样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47286074/