2017-03-01 49 views
0

我已经实现了自己的自定义按钮,并且效果很好。删除UIButton上的禁用色调

import Foundation 
import UIKit 

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

     super.init(coder: aDecoder) 
    } 

    override var isEnabled: Bool { 
     didSet { 
      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 
      } 
     } 
    } 
} 

设置我GhostYouButton在viewDidLoad中()被禁用:

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

像我期待它因此,它会变成灰色:

enter image description here

但是...正如你所看到的,UIButton的标题已经淡出。我希望这是与边框完全相同的颜色。我如何做到这一点?

+0

您需要添加按钮上方的标签,还可以设置按钮上的文字。而且可能你的看法hirarchy并不完美。 –

+0

如果按钮本身已经有标题,那么在按钮上添加一个标签会让我觉得很奇怪。这是唯一的方法吗? –

+0

@RutgerHuijsmans。我想你错过super.viewDidLoad()到你的覆盖func viewDidLoad()。 –

回答

1

使用此行

if (self.isEnabled == false){ 
    : 
    self.setTitleColor(UIColor.gray, for: .normal) 
    : 
    } 
    else{ 
    : 
    self.setTitleColor(UIColor.green, for: . disabled) 
    : 
    } 
0

现在,它看起来像你直接设置标签的标题颜色。虽然这是有效的,但当使用UIButton时(如您所遇到的),设置标题颜色的最佳方式并不是这个属性可以根据按钮的状态而改变。相反,你应该使用的UIButton的setTitleColor:forState:方法,让你在风格更细粒度控制和按钮,该按钮的阶段变化的外观:https://developer.apple.com/reference/uikit/uibutton/1623993-settitlecolor?language=swift

使用这种方法,你可以通过在控制状态如残疾人,高亮,等:https://developer.apple.com/reference/uikit/uicontrolstate