简体   繁体   English

viewDidLoad之外的闭包

[英]Closures outside viewDidLoad

I'd like to create a simple app without Storyboard. 我想创建一个没有Storyboard的简单应用。 I've created a closure outside the viewDidLoad method, which represents a title on the screen. 我在viewDidLoad方法外部创建了一个闭包,该闭包表示屏幕上的标题。 My problem is that the code contains duplicated lines view.addSubview(label) and it positions the label to the wrong place. 我的问题是代码包含重复的行view.addSubview(label)并将其放置在错误的位置。

Could you please help me solving this issue? 您能帮我解决这个问题吗?

class HomeVC: UIViewController {
    let titleLabel: UILabel = {
        let view = UIView()
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(label)
        label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        label.text = "Hello"
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(titleLabel)
    }
}

I think you want to set the label at the center of HomeVC's view, the problem in the above code is that you are making a new view and place the label inside the view and thats not what you want , so 我认为您想将标签设置在HomeVC视图的中心,上面代码中的问题是您要创建一个新视图并将标签放置在视图内,这不是您想要的,所以

You just make label first like this: 您只需像这样首先制作标签:

let titleLabel: UILabel = {

            let label = UILabel()
            label.translatesAutoresizingMaskIntoConstraints = false

            label.text = "Hello"
            return label
        }()

and then in viewDidLoad add this label as subview of view and apply constraints 然后在viewDidLoad将此标签添加为视图的子视图并应用约束

override func viewDidLoad() {
    super.viewDidLoad()
        view.addSubview(titleLabel)
        setupTitleLabel()
}

func setupTitleLabel() {
        titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        //you also need to give the label height and width constraints to label here...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM