Evgeniy Kleban
Evgeniy Kleban

Reputation: 6975

Add programmatically constraint to text view

I have construction like follow:

enter image description here

You can see that i add fixed height constraint for text view. However, its wrong, because i cant know text view height before app launch. I will load data and sometime height might be 100, and next time it will be 1000, depending on content.

What i want is, calculate expected text view height and add fixed height constraint programmatically, before view load.

Upvotes: 0

Views: 648

Answers (3)

keshav vishwkarma
keshav vishwkarma

Reputation: 1852

You can also update and access any constraints without IBOutlet reference of your constraint. Try KVConstraintExtensionsMaster library.

/** applyHeightConstraint method will add a new height constraint on yourView 
  * If yourView already have height constraint, It will update the constraint constant too. 
  */
  [yourView applyHeightConstraint:80]; // this will add height constraint
  [yourView applyHeightConstraint:100]; // this will updates height constraint

// To access height constraint 
  [yourView accessAppliedConstraintByAttribute:NSLayoutAttributeHeight completion:^(NSLayoutConstraint *expectedConstraint){
    if (expectedConstraint) {
        // do here additional stuff 
        expectedConstraint.constant = 150;
        // To update constant with nice animation
        [yourView updateModifyConstraintsWithAnimation:NULL];
    }
}];

Upvotes: 0

Vishnu gondlekar
Vishnu gondlekar

Reputation: 3956

First thing you need to do is, to create IBOutlet of your constraint. IBOutlet for constraint is created in same way as you create Outlet for view elements. Once you create outlet you'll have

@property (weak) IBOutlet NSLayoutConstraint *constraintName;

added in your code. All you have to do next is set the text for your text view and change the constraint.

constraintName.constant = 50 //assuming 50 is height of your text view.

Once you update constraint call

self.view.layoutIfNeeded()

layoutIfNeeded forces the receiver to layout its subviews immediately if required.

Upvotes: 1

SHEBIN
SHEBIN

Reputation: 162

add reference outlet for the height constraint. change constraint outlet value constant based on the content value height.

@property (weak) IBOutlet NSLayoutConstraint *constraintTextviewHeight;

change value by programatically as follows constraintTextviewHeight.constant=100 or 200 or any required height

Upvotes: 1

Related Questions