Utku Demir
Utku Demir

Reputation: 37

Which properties do constraints affect?

I'm trying to understand constraints' logic and there is somethin I cannot find out...

I created a custom UIButton and add some constraints to change it's width and height and it's working fine. But I cannot find the new width and height values of the button. How can I get these values after constraints change them?

Here is my code...

import Foundation
import UIKit

class RoundedButton: UIButton {

    class func make (text:String, color:UIColor) -> RoundedButton {

        let button = self.buttonWithType(UIButtonType.System) as RoundedButton
        button.frame = CGRectMake(0, 0, 150, 40)
        button.layer.cornerRadius = 20
        button.layer.borderColor = color.CGColor
        button.layer.borderWidth = 2

        button.setTitle(text, forState: UIControlState.Normal)
        button.setTitleColor(color, forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont(name: "OpenSans-Semibold", size: 14)
        return button
    }

    func resizeAndPlace(width:CGFloat, height:CGFloat)
    {
        self.setTranslatesAutoresizingMaskIntoConstraints(false)

        let widthCons = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: width)

        let heightCons = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: height)

        self.superview!.addConstraint(widthCons)
        self.superview!.addConstraint(heightCons)

        println(self.frame.width) // 150 and never changes
    }
}

Upvotes: 1

Views: 151

Answers (2)

vacawama
vacawama

Reputation: 154631

The reason you aren't seeing the constraints take effect is that layout hasn't happened yet. If you call:

self.layoutIfNeeded()

immediately after setting the constraints, then the values will be reflected in the frame.

Upvotes: 3

Eric
Eric

Reputation: 2097

There are a couple ways you can do this in your sample code. You could actually store the width and height variables from resizeAndPlace as properties in your RoundedButton class, but a better solution would be to store the constraints themselves and do widthConstraint.constant and heightConstraint.constant. Then when you want to change the constraints, you can just change the constants instead of removing the old constraints and adding new constraints.

Upvotes: 1

Related Questions