UIButton子视图在子类中偏移

时间:2017-11-06 14:25:50

标签: ios swift uibutton

我有一个UIButton子类,用于显示按钮的选定状态。所选状态只是在按钮视图的底部放置一条粗黑线,未选中时隐藏黑线。但是,在UIButton子类中使用它时,黑线视图会偏移。我试过玩插图,但我不认为这是问题所在。这是我的子类:

class TabButton: UIButton {

    private var height:CGFloat = 5
    private var selectedIndicator:UIView?

    override var isSelected: Bool {
        didSet { 
            selectedIndicator?.isHidden = !isSelected 
        }
    }

    fileprivate func initializeSelector(_ frame: CGRect) {
        selectedIndicator = UIView(frame: CGRect(x: 0, y: frame.size.height - height, width: frame.size.width, height: height))
        selectedIndicator?.backgroundColor = UIColor.black 
        self.addSubview(selectedIndicator!)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        initializeSelector(self.frame)
    }
}

所需按钮应如下所示:

enter image description here

但它看起来像这样:

enter image description here

任何人都可以帮助我了解这里发生了什么以及如何解决它?谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个,在layoutSubviews中你得到最后一帧:

override layoutSubviews() {
    super.layoutSubviews()
    selectedIndicator.frame = CGRect(x: 0, y: frame.size.height - height, width: frame.size.width, height: height)
}

答案 1 :(得分:1)

selectedIndicator的框架仅在调用initializeSelector时设置一次。当按钮更改其框架时,更改子视图的框架,您需要手动更新selectedIndicator的框架。

为此,您需要覆盖UIView的{​​{3}}方法。

override layoutSubviews() {
    super.layoutSubviews()
    selectedIndicator?.frame = CGRect(x: 0, y: frame.size.height - height, width: frame.size.width, height: height)
}

请参阅https://regex101.com/r/Y7znBy/1回答,了解何时调用layoutSubviews()