将UIButton的大小设置为在情节提要上显示



我有一个按钮类,它可以动态调整自己的大小,但在故事板中,宽度和高度不正确。我想在故事板上更新尺寸。

否则,除非我构建它,否则很难对齐或查看按钮的实际大小

如有任何帮助,我们将不胜感激!谢谢要了解我的意思,请查看此屏幕截图。

@IBDesignable class PrimaryButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
shared()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
shared()
}
override  func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
shared()
}
func shared() {
//TODO: add any custom settings here
self.layer.cornerRadius = 4.0
self.clipsToBounds = true
self.layer.backgroundColor = UIColor.blue.cgColor
self.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: UIControl.State.normal)
self.contentEdgeInsets = UIEdgeInsets(top: 4, left: 12, bottom: 4, right: 12)
self.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 16.0)
self.sizeToFit()
//Disabled
self.setTitleColor(#colorLiteral(red: 0.6666666865, green: 0.6666666865, blue: 0.6666666865, alpha: 1), for: UIControl.State.disabled)
setBackgroundColor(UIColor.gray, for: UIControl.State.disabled)
}

}
//background color method
extension PrimaryButton {
private func image(withColor color: UIColor) -> UIImage? {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func setBackgroundColor(_ color: UIColor, for state: UIControl.State) {
self.setBackgroundImage(image(withColor: color), for: state)
}
}

您可以添加宽度约束并将其检查为"在运行时删除">

最新更新