为自定义UIButton设置禁用状态

时间:2017-03-01 03:37:48

标签: ios swift uibutton

我创建了以下自定义UIButton:

import Foundation
import UIKit

class WhiteGhostYouButton: UIButton {

    required public init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

        self.backgroundColor = UIColor.clear
        self.titleLabel?.textColor = UIColor.white
        self.borderWidth = 2
        self.borderColor = UIColor.white
        self.cornerRadius = 23
    }
}

这很棒!

现在我还想为此按钮实现自定义禁用状态。

我该如何解决这个问题?

这似乎不起作用:

import Foundation
import UIKit

class GhostYouButton: UIButton {
    required public init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

        if (self.isEnabled == false) {
            self.backgroundColor = UIColor.clear
            self.titleLabel?.textColor = Constant.disabledGrayColor
            self.tintColor = Constant.disabledGrayColor
            self.borderColor = Constant.disabledGrayColor
            self.borderWidth = 2
            self.cornerRadius = 20
        } else {
            self.backgroundColor = UIColor.clear
            self.titleLabel?.textColor = Constant.mainGreenColor
            self.tintColor = Constant.mainGreenColor
            self.borderColor = Constant.mainGreenColor
            self.borderWidth = 2
            self.cornerRadius = 20
        }
    }
}

禁用我的按钮的viewDidLoad:

override func viewDidLoad() {
    self.nextButton.isEnabled = false
}

2 个答案:

答案 0 :(得分:2)

我认为您可以尝试实施I dont like politic :-( but still read about it :-) _ because its funny . :D and unpredictable :)的{​​{1}}:

didSet

希望这可以帮助你:)

答案 1 :(得分:0)

根据禁用状态等状态自定义WhiteGhostYouButton。您需要在自定义类中添加drawRect方法,如下面的代码片段所示。

class WhiteGhostYouButton: UIButton {

    override func draw(_ rect: CGRect) {
    super.draw(rect)
    if self.isEnabled = false {
   //Customize UI here        
      } esle {
      }
   }
}

在按下按钮的任何事件上,可以按照下面的代码片段强制重新呈现视图

 @IBAction func button_Pressed(sender: AnyObject) {
         sender.setNeedsDisplay()
    }