我有一个继承自class
的自定义UIButton
。我想要完成的事情是根据按钮的启用状态(即启用或禁用)设置tintColor
属性。
有没有办法实现这个目标?
这是我的班级:
class ButtonsPostMenu: UIButton
{
override func awakeFromNib()
{
titleLabel?.font = UIFont(name: Font_AvenirNext_Medium, size: 14)
tintColor = UIColor.white
}
}
答案 0 :(得分:8)
您可以覆盖isEnabled属性来实现此目的。 tintColor将根据按钮的isEnabled状态自动更改:
class ButtonsPostMenu:UIButton {
//......
override var isEnabled: Bool {
didSet{
if self.isEnabled {
self.tintColor = UIColor.white
}
else{
self.tintColor = UIColor.gray
}
}
}
//......
}
答案 1 :(得分:3)
这是您的课程:添加changeStateOfButton
自定义方法,用于管理UIButton
class ButtonsPostMenu: UIButton
{
override func awakeFromNib()
{
titleLabel?.font = UIFont(name: Font_AvenirNext_Medium, size: 14)
tintColor = UIColor.white
}
func changeStateOfButton() {
if self.isEnabled {
self.tintColor = UIColor.red // Set your color when button is enabled
}
else {
self.tintColor = UIColor.yellow // Set your color when button is disabled
}
}
}
只需调用上述方法,就像根据启用/禁用UIButton
设置颜色一样。
答案 2 :(得分:1)
您可以尝试像这样复制setX(_ x: X, forState: State)
API:
private class TintColorButton: UIButton {
private var tintDict: [State.RawValue: UIColor] = [:]
private var store: Set<AnyCancellable> = []
override init(frame: CGRect) {
super.init(frame: frame)
publisher(for: \.isHighlighted).sink { [weak self] _ in self?.applyTintColor() }.store(in: &store)
publisher(for: \.isEnabled).sink { [weak self] _ in self?.applyTintColor() }.store(in: &store)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setTintColor(_ color: UIColor?, forState state: State) {
tintDict[state.rawValue] = color
applyTintColor()
}
private func applyTintColor() {
tintColor = tintDict[state.rawValue] ?? tintDict[State.normal.rawValue]
}
}
答案 3 :(得分:0)
std::tgamma(7+1)
答案 4 :(得分:0)
我认为图像过滤是个不错的选择。
btn.setImage(image, for: UIControl.State.normal)
btn.setImage(image.disabled, for: UIControl.State.disabled)
使用CoreImage进行图像过滤
extension UIImage{
var disabled: UIImage?{
let ciImage = CIImage(image: self)
let grayscale = ciImage?.applyingFilter("CIColorControls",
parameters: [ kCIInputSaturationKey: 0.0 ])
if let gray = grayscale{
return UIImage(ciImage: gray)
}
else{
return nil
}
}
}
当然,在Swift 5中