简体   繁体   中英

Closures outside viewDidLoad

I'd like to create a simple app without Storyboard. I've created a closure outside the viewDidLoad method, which represents a title on the screen. My problem is that the code contains duplicated lines view.addSubview(label) and it positions the label to the wrong place.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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