Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

heightAnchor.constraint does not work (Apple FoodTracker Tutorial using Swift)

I've been doing a iOS tutorial from Apple; Start Developing iOS Apps. https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ImplementingACustomControl.html#//apple_ref/doc/uid/TP40015214-CH19-SW1

In the tutorial, I added a button which has the size constraint of 44.0x44.0 on a Horizontal stack view. However, the simulator shows a larger button.

looks the size constraints do not work.

My code is below. Can you give advices to fix?

class RatingControl: UIStackView {
    //MARK: Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupButtons()
    }
    required init(coder: NSCoder) {
        super.init(coder: coder)
        setupButtons()
    }

    //MARK: Private Methods
    private func setupButtons() {
        let button = UIButton()
        button.backgroundColor = UIColor.red
        // Add constraints
        button.translatesAutoresizingMaskIntoConstraints = false
        button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
        button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true
        addArrangedSubview(button)
    }
}

The problem was fixed by changing the property of the StackView.

like image 390
Thomas ISHIGAKI Avatar asked Oct 06 '17 12:10

Thomas ISHIGAKI


1 Answers

I had the same issue. It was because I didn't drag the new Horizontal StackView into the existing Vertical StackView. Instead, I dragged it into the main View. If you look at the Document Outline, the the new StackView should be a child of the first Vertical StackView, and just under the Photo Image View.

It's in the instructions, but it was unclear for me.

  • Correct - Screen shot of IB
  • Wrong - Screen shot of IB
like image 122
NoBot Avatar answered Nov 18 '22 09:11

NoBot