gpt4 book ai didi

swift - 自定义按钮不显示标题

转载 作者:行者123 更新时间:2023-11-28 05:39:01 26 4
gpt4 key购买 nike

我在 Swift 中自定义了一个 UIButton。但我无法让标题正确显示。这是我的课:

import UIKit

final class CustomButton: UIButton {
var cornerRs: Bool = false
override init(frame: CGRect){
super.init(frame: frame)
}
convenience init(bordercolor : CGColor = UIColor.black.cgColor,
backGroundColor : UIColor = UIColor.black, foreGroundColor : UIColor = UIColor.black,borderThickness : CGFloat = 1,borderRadius:Bool = false,title : String, font : UIFont = UIFont.preferredFont(forTextStyle: .body)) {
self.init(frame: .zero)
self.translatesAutoresizingMaskIntoConstraints = false
self.cornerRs = borderRadius
self.layer.borderWidth = borderThickness
self.layer.borderColor = bordercolor
self.setTitleColor(foreGroundColor, for: UIControl.State.normal)
self.setTitle(title, for: UIControl.State.normal)
self.backgroundColor = backGroundColor
}

required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

override func layoutSubviews() {
setup()
}

func setup() {
self.clipsToBounds = true
self.layer.cornerRadius = (self.cornerRs) ? self.frame.size.height / 2.0 : 0
}
}

这是我的实例化:

button = CustomButton(bordercolor: UIColor.blue.cgColor, backGroundColor: UIColor.blue, foreGroundColor: .white, borderThickness: 1, borderRadius: true, title: "Click here!", font: UIFont.preferredFont(forTextStyle: .headline))

我在这里做错了什么?

最佳答案

嗯,我明白了。您应该在自己的 layoutSubviews() 覆盖内调用 super.layoutSubviews(),以便正确显示内部 View (如标题标签)。

关于swift - 自定义按钮不显示标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57609047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com