How to put a UIView inside a UISrollView in Swift

Asked 2 years ago, Updated 2 years ago, 32 views

Put a scroll view inside the main view on the storyboard I want to put a dynamically generated UIView in it I can't see the view because something's wrong.

class MainViewController: UIViewController {
    @IBOutlet weak var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let view = UIView()
        view.backgroundColor = UIColor.red

        view.widthAnchor.constraint(equalToConstant: 100).isActive = true
        view.heightAnchor.constraint(equalToConstant: 150).isActive = true

        scrollView.addSubview(view)
    }

}

What's the problem?

view.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true

If you insert the same code, the error "Unable to activate constraint with anchors" will kill you.

swift ios

2022-09-22 12:44

2 Answers

Found and resolved in Stack Overflow.

class MainViewController: UIViewController {
    @IBOutlet weak var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let view = UIView()
        view.backgroundColor = UIColor.red

        view.widthAnchor.constraint(equalToConstant: 100).isActive = true
        view.heightAnchor.constraint(equalToConstant: 150).isActive = true

        view.translatesAutoresizingMaskIntoConstraints = false
        scrollView.addSubview(view)
        view.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
        view.topAnchor.constraint(eqaulTo: scrollView.topAnchor).isActive = true
    }

}

Give the translates Autoresizing Mask Into Constraints, add the subview first, and then give the constraint.

Note) Link name


2022-09-22 12:44

I haven't used Anchor

Specify the contentSize of the scrollView~

https://developer.apple.com/reference/uikit/uiscrollview


2022-09-22 12:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.