ios - 在快速布局冲突中创建自定义按钮
问题描述
所以我尝试子类化 UIButton 来创建一个定制的按钮,确切地说是这样的
所以我遵循了互联网上的一些说明,因为那个人声明了框架而不是做
button.translatesAutoresizingMaskIntoConstraints = false
所以我试图“主动”对我的自定义按钮做这样的事情
class BigButton: UIButton {
private let myTitleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 1
label.textAlignment = .center
return label
}()
private let icon: UIImageView = {
let icon = UIImageView()
icon.contentMode = .scaleAspectFit
return icon
}()
private var viewModel: MyCustomBigButton?
override init(frame: CGRect) {
self.viewModel = nil
super.init(frame: frame)
}
init(with viewModel: MyCustomBigButton) {
super.init(frame: .zero)
self.viewModel = viewModel
addSubview(myTitleLabel)
addSubview(icon)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func configure(with viewModel: MyCustomBigButton) {
myTitleLabel.text = viewModel.title
icon.image = UIImage(named: viewModel.imageName)
}
override func layoutSubviews() {
super.layoutSubviews()
NSLayoutConstraint.activate([
icon.topAnchor.constraint(equalTo: self.topAnchor, constant: 5),
icon.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0),
icon.heightAnchor.constraint(equalToConstant: frame.height*0.5),
icon.widthAnchor.constraint(equalToConstant: frame.width*0.9),
myTitleLabel.topAnchor.constraint(equalTo: icon.bottomAnchor, constant: 5),
myTitleLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0),
myTitleLabel.widthAnchor.constraint(equalToConstant: frame.width*0.9),
myTitleLabel.heightAnchor.constraint(equalToConstant: frame.height*0.2)
])
}
}
将 NSlayout 添加到 UIButton 的子类,希望它可以工作,结果它与我为按钮设置的主布局冲突
class BerandaViewController: UIViewController {
var didSendEventClosure: ((BerandaViewController.Event) -> Void)?
let pesanButton: BigButton = {
let button = BigButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .blue
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .purple
view.addSubview(pesanButton)
NSLayoutConstraint.activate([
pesanButton.widthAnchor.constraint(equalToConstant: 200),
pesanButton.heightAnchor.constraint(equalToConstant: 60),
pesanButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
pesanButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
}
那么,我的代码有什么问题?还有其他参考资料可以让我学习如何正确构建它吗?谢谢
来自 swiftUI 让我错过了 swiftUI 创建自定义按钮的方式
解决方案
推荐阅读
- c# - 如何验证列表中的用户输入 C#
- r - How to use different engine parameters for each fold with tidymodels during crossvalidation?
- vuejs3 - 如何在 vuejs3/vite 中使用 sass
- janusgraph - 当在 has() 子句中使用索引属性时,JanusGraph 有时会返回空结果
- javascript - 如何获取克隆选项选择菜单的值?
- python - Heroku 部署:ModuleNotFoundError:没有名为“django”的模块
- html - jQuery 将临时 DOM 操作为 HTML 字符串
- php - 可以嗅出通过 cURL 发送的变量吗?
- php - 如何比较 PHP 中的两个嵌套数组?
- c - 可以使用选项字节将用户数据永久存储在 STM32 微控制器的内部闪存中吗?