Search code examples
iosswiftconstraintsprogrammatically-created

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

Solution

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