简体   繁体   中英

Autolayout frame update in viewDidLoad

I have a custom subview defined this way:

class CustomSubview:UIView {

 let contentView = ContentView(frame: .zero) //ContentView is another custom subview

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

 private func setupContentView() {
    contentView.translatesAutoresizingMaskIntoConstraints = false
    contentView.backgroundColor = UIColor.clear
    addSubview(contentView)
    contentView.leftAnchor.constraint(equalTo: leftAnchor, constant:10).isActive = true
    contentView.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true
    contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
    contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    contentView.clipsToBounds = true
    contentView.isUserInteractionEnabled = true
    contentView.layoutIfNeeded()
     NSLog("Contentview frame \(contentView.frame)")
}
}

The problem is even after calling layoutIfNeeded, the frame is still CGRect.zero. Why is that? How do I ensure bounds to be updated immediately?

In CustomSubview class, implement:

override func layoutSubviews() {
    super.layoutSubviews()
    NSLog("In layoutSubviews() - Contentview frame \(contentView.frame)")
}

That's where you have the actual frame. Note that it will be called anytime your instance of CustomSubview changes, such as on device rotation (assuming you have it set up to change size when its superview changes size).

So, you would want to calculate how many "thumbnails" you want to display, and either add or remove them as needed.

Change your

contentView.layoutIfNeeded()

to

contentView.setNeedsLayout()
layoutIfNeeded()

You need to tell the CustomSubview object to lay itself out again, not just the contentView .

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