Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set translatesAutoresizingMaskIntoConstraints

In an attempt to solve an Auto-Layout issue related to programmatically adding sub views to a scroll view, I have run into many references throughout the internet that, in various scenarios say to set translatesAutoresizingMaskIntoConstraints = YES or translatesAutoresizingMaskIntoConstraints = NO, depending on the case.

However, in Swift, when I type:

var view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false

I get the in-line error: Cannot assign to 'translatesAutoresizingMaskIntoConstraints' in 'view'. Why? Because, when inspected, you'll find that it's a parameterless function, not a property.

I've gotten around this by subclassing, but it's a major inconvenience to have to subclass every view I'm dealing with, just to set translatesAutoresizingMaskIntoConstraints:

class CardView: UIView {
    override func translatesAutoresizingMaskIntoConstraints() -> Bool {
        return false
    }
}

Does anyone know a way around this, or can shed light on the discrepancy between what the general internet councils tell you and what you can actually do, in Swift?

like image 747
Albert Bori Avatar asked Nov 20 '14 19:11

Albert Bori


People also ask

What does translatesAutoresizingMaskIntoConstraints mean?

translatesAutoresizingMaskIntoConstraints. A Boolean value that determines whether the view's autoresizing mask is translated into Auto Layout constraints.

How do I enable constraints in Swift?

addConstraint(constY); var constW:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute. Width, relatedBy: NSLayoutRelation. Equal, toItem: new_view, attribute: NSLayoutAttribute. Width, multiplier: 1, constant: 0); self.

What is NSLayoutConstraint in Swift?

The relationship between two user interface objects that must be satisfied by the constraint-based layout system.


1 Answers

translatesAutoresizingMaskIntoConstraints is actually a method on UIView and not a property.

The syntax works because ObjC lets you use dot-notation for calling methods as well (there's a whole other discussion on how properties actually auto-generate getter/setter methods).

Use the method instead of trying to use the property notation from ObjC

view.setTranslatesAutoresizingMaskIntoConstraints(false) 
like image 144
Mike Welsh Avatar answered Sep 24 '22 00:09

Mike Welsh