Can't change UITextView frame size programmati

2019-06-26 13:05发布

问题:

I've insert an UITextView in a view with Interface builder, now I would like to change its frame size so it fits the content programmatically. The problem is that the size seems locked and unchangable from code because of the constraints. If I disable in file inspector use auto-layout every object gets the constraints removed, but I only want to change the UITextView not the other objects.

[textview setFrame:CGRectMake(x,y,w,h)]; // This doesn't do anything to the uitextview

回答1:

If you're using constraints, then you must use constraints to change the UITextView's size. Set up outlets in the nib to get access from your code to the constraints you need to change. You can set a constraint's constant in real time, and this is usually sufficient.

Just to clarify the reasons for this: you cannot change a view's frame if it is being positioned by constraints. Well, you can, but it's fruitless and it's bad practice. This is because the constraints themselves will be used by the layout system to change the view's frame for you! Thus, you can change the frame, but the layout system will then read and resolve the constraints and change the frame back again.

Think of constraints as a "to-do list" for the layout system. Constraints do nothing in and of themselves; they are just a list of rules. It is the layout system that does the work (when layoutSubviews is called). Every time layout is needed, the layout system comes along, reads the constraints, works out how to obey them, and does so - by setting the frames of your views. You need to work with that system, not against it.



回答2:

All of UIViews and classes are inherited from UIView have same property is: "Lock" in XIB file. If you want to change frame of those views. You must set Lock is "Nothing"



回答3:

If you don't care to become a constraint expert, do it like this (in your view controller.)

@property UITextView *textView;

//Create UITextView on the fly in viewWillAppear

rect = CGRectMake(194., 180., 464., 524.);
_textView =  [[UITextView alloc] initWithFrame:rect];
[self.view addSubview:_textView];

//Now you can resize it at will

 CGRect oldFrame = _textView.frame;
 CGRect newFrame = oldFrame;
 newFrame.size.height += 300;
 [_textView setFrame:newFrame];