Can't change UITextView frame size programmatically

给你一囗甜甜゛ 提交于 2020-01-03 16:55:19

问题


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];


来源:https://stackoverflow.com/questions/14652598/cant-change-uitextview-frame-size-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!