在 willWillLayoutSubviews()
中,我调用了我创建的 UIButton 的
方法 setTileTheme()
。结果如下所示 - 重复的 UILabel
出现在另一个下。我已经尝试从 viewDidLoad()
等调用我的方法,但它没有帮助。
有人知道我为什么会遇到这个问题吗?
func setTileTheme(image: UIImage, title: String) {
self.translatesAutoresizingMaskIntoConstraints = false
tintColor = .green
backgroundColor = .white
setBorder(width: 1.5, color: .lightGray)
roundCorners(radius: 5)
self.layer.masksToBounds = true
let width = self.frame.size.width
let height = self.frame.size.height
let offset: CGFloat = width/4.5
let titleLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: width, height: 30))
titleLabel.center = CGPoint(x: width/2, y: height-offset)
titleLabel.text = title
titleLabel.font = titleLabel.font.withSize(15)
titleLabel.textAlignment = .center
titleLabel.textColor = .darkGray
self.insertSubview(titleLabel, at: 0)
imageEdgeInsets = UIEdgeInsets(top: height/8, left: width/4, bottom: height*3/8, right: width/4)
setImage(image, for: .disabled)
setImage(image.withRenderingMode(.alwaysTemplate), for: .normal)
}
最佳答案
UIButton 已经有 titleLabel 和 imageView。您正在做的是创建一个新标签并将其添加到按钮 View 中,这不会替换默认标签。
所有你需要的是
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
return CGRectCGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: 30)
}
func setTileTheme(image: UIImage, title: String) {
self.translatesAutoresizingMaskIntoConstraints = false
tintColor = .green
backgroundColor = .white
setBorder(width: 1.5, color: .lightGray)
roundCorners(radius: 5)
self.layer.masksToBounds = true
let width = self.frame.size.width
let height = self.frame.size.height
let offset: CGFloat = width/4.5
self.titleLabel?.text = title
self.titleLabel?.font = titleLabel.font.withSize(15)
self.titleLabel?.textAlignment = .center
self.titleLabel?.textColor = .darkGray
imageEdgeInsets = UIEdgeInsets(top: height/8, left: width/4, bottom: height*3/8, right: width/4)
setImage(image, for: .disabled)
setImage(image.withRenderingMode(.alwaysTemplate), for: .normal)
}
我相信您正在尝试设置按钮的标题标签框架,您可以通过覆盖 titleRect
编辑:
我可以看到您也在尝试将插图设置为 Button 的图像。将 inset 添加到 imageView 只会将图像移动到 imageView 中,但 imageView 框架保持不变。相反,如果您想影响 imageView 的框架本身,那么您可以简单地覆盖
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
//whatever calculation you wanna provide
//for example
return CGRect(x: (self.bounds.size.width/2 + 5), y: self.bounds.size.height/2, width: (self.bounds.size.width/2 - 5), height: self.bounds.size.height)
}
希望对你有帮助
关于ios - UIButton 中的重复 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46786738/