swift - 如何在架构 MVC 中安排视图?通过代码编码时
问题描述
我正在学习架构 MVC,我通过代码编写接口。我正在尝试链接 VIEW 和 CONTROLLER。但它不起作用。我的错误是什么?
控制器:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
ViewExample.setupUI()
}
}
看法:
import UIKit
class ViewExample: UIView {
static func setupUI() {
let view = UIView()
let labelTitle: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Hello, world!"
return label
}()
view.backgroundColor = .white
view.addSubview(labelTitle)
NSLayoutConstraint.activate([
labelTitle.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
labelTitle.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
labelTitle.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
我明白为什么需要静态。为什么它对我不起作用?我在 github 上没有找到任何好的例子。因此,我不得不求助于你
解决方案
I don't see why you would use static
, you want to set up the UI of a UIView
's instance, thus no need to have a static
class method.
In your ViewExample
:
import UIKit
class ViewExample: UIView {
func setupUI() {
let labelTitle: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Hello, world!"
return label
}()
self.backgroundColor = .white
self.addSubview(labelTitle)
NSLayoutConstraint.activate([
labelTitle.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 10),
labelTitle.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10),
labelTitle.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10),
])
}
override init(frame: CGRect){
super.init(frame: frame)
setupUI()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupUI()
}
}
In your ViewController
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let view = ViewExample(frame: (x: 0, y: 0, width: 200, height: 50)) //Change the frame according to where you want to position your view
self.addSubview(view)
}
}
推荐阅读
- javascript - 如何在chrome开发人员工具中自动化需要在javascript中单击按钮的代码
- c# - C# BLE DeviceConnectionChanged 事件多次触发,直到关闭设备
- python-3.x - Tesseract-OCR 无法在某些图像中找到文本
- r - 使用插入符号的岭逻辑回归系数的标准误差
- apache-poi - 使用 POI 限制编辑 Word 文件中的特定部分
- java - 解压后日期以毫秒的形式出现 - 不同机器上的不同行为
- json - 有没有办法从 Go 中的给定 JSON 中提取 JSON Schema?
- java - 如何将 JTextArea 对象放置在 JPanel 上的某个位置?
- python - 使用此 Python 脚本将立方体贴图转换为 equirectangular
- function - Lua - 连接传递给函数的几个参数,直到满足条件,然后将字符串传递给下一个函数