【问题标题】:Custom UIButton class does not show title自定义 UIButton 类不显示标题
【发布时间】:2020-06-29 13:48:55
【问题描述】:

我创建了一个自定义 UIButton 类。但是标题没有出现。我只得到背景颜色和圆角。但标题不可见。

当我在模拟器 iOS 13+ 中运行它时,它的标题显示为白色。但是当我在我的设备(即 iOS 12.4)中运行时,它无法正常工作。

这是我的代码:

public class CornerButton : UIButton {

    public override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
        self.layoutIfNeeded()

    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
        self.layoutIfNeeded()

    }

    func setup() {
        self.titleLabel?.font = UIFont(name: "Poppins-SemiBold", size: 12)
        self.backgroundColor = UIColor(named: "BarColor")
        self.setTitleColor(.white, for: .normal) // this line is not working
        self.clipsToBounds = true

    }

    public override func layoutSubviews() {
        self.roundCorners(corners: [.topRight,.bottomLeft], radius: 10)
    }

}

【问题讨论】:

  • 分享按钮CornerButton的用法!
  • @Vicky_Vignesh 我在情节提要中有按钮。我给它分配了这个自定义类。一切正常。只是标题没有显示。
  • 怀疑这行self.roundCorners(corners: [.topRight,.bottomLeft], radius: 10)评论一下试试
  • @Sh_Khan 成功了。我从layoutSubviews() 中删除了该行并将其放在setup() 的第一行。
  • 我应该将其添加为答案还是飞行

标签: ios swift uibutton


【解决方案1】:

您需要拨打super.layoutSubviews()

public override func layoutSubviews() {
    super.layoutSubviews()
    self.roundCorners(corners: [.topRight,.bottomLeft], radius: 10)
}

顺便说一句,您不需要layoutSubviews,因为当您需要根据视图的实际测量边界进行制作时使用它,并且当您设置静态半径时,您可以省略它

【讨论】:

  • 按钮在故事板中。它有标题
猜你喜欢
  • 2015-01-07
  • 2021-09-21
  • 2016-11-21
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多