gpt4 book ai didi

ios - Swift:如何以编程方式创建可重用 View ?

转载 作者:行者123 更新时间:2023-11-28 06:02:13 26 4
gpt4 key购买 nike

假设我正在描述我自己的 UIView,我们称它为 HeaderView。我希望 HeaderView 具有完全相同的属性,但只是标签文本不同。这是我目前的方式:

private let headerView: UIView = {
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

let view = UIView()
view.backgroundColor = .white
view.heightAnchor.constraint(equalToConstant: 65).isActive = true

let label = UILabel()
label.font = UIFont.systemFont(ofSize: 30)
label.textAlignment = .left
label.textColor = .black
label.text = "Search"

view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 5).isActive = true

return view
}()

我会如何使用它:

 view.addSubview(headerView)
headerView.translatesAutoresizingMaskIntoConstraints = false
headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
headerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true

如果我想要其中 3 个带有不同文本的标题 View 怎么办?我如何将其变成可重用的编程 View ?

最佳答案

您可以创建 UIView 的子类并在任何地方重用它

class HeaderView: UIView {

let innerview = UIView()
let innerlabel = UILabel()

override init(frame: CGRect) {
super.init(frame: frame)
sharedLayout()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedLayout()
}

private func sharedLayout() {

self.addSubview(innerview)
self.innerView.backgroundColor = UIColor.red
innerview.translatesAutoresizingMaskIntoConstraints = false
innerview.trailingAnchor.constraint(equalTo:self.trailingAnchor).isActive = true
innerview.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
innerview.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
innerview.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

// configure other items here
}

}

关于ios - Swift:如何以编程方式创建可重用 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49283724/

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