首页 > 解决方案 > 如何在架构 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 上没有找到任何好的例子。因此,我不得不求助于你

标签: swiftmodel-view-controlleruikit

解决方案


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)
      }

   }

推荐阅读