Resize UITextField horizontally with text using Auto Layout

坚强是说给别人听的谎言 提交于 2019-11-30 16:55:26

问题


An example project to demonstrate the below issue can be found here: https://github.com/markdorison/UITextFieldContentSizeExample/

I am attempting to have a UITextField grow/shrink its width with the text content it contains using Auto Layout. I have created leading and trailing constraints with a priority of 749 (as opposed to the default: 1000). I have also tried lowering the priority of these constraints all the way down to 1, but this does not seem to have a noticeable effect on the behavior.

By listening to the UIControlEventEditingChanged event, I am triggering a reset of the intrinsicContentSize:

- (IBAction)textFieldDidChange:(UITextField *)textField {
    [UIView animateWithDuration:0.1 animations: ^{
        [textField invalidateIntrinsicContentSize];
    }];
}

This approach almost works. There are two issues:

  1. I am setting a placeholder. However wide the placeholder is, the width of the UITextField's intrinsicContentSize will never drop below it. So if the placeholder's width is 130, and I begin to type, the text view's width will remain at 130 until what I am typing reaches a width greater than 130; after this the text view will grow.

  2. In my example I have placed a UITextView below the UITextField. When I type in the UITextField, its width grows as expected. I can then tap into the UITextView and edit the text. If I then go back and edit the UITextView, its width no longer grows/shrinks as expected. The values being returned by the UITextField's intrinsicContentSize property go from being standard-looking integers like {192, 28}, to {191.536, 27.959999}.

Any help would be appreciated!


回答1:


I am setting a placeholder. However wide the placeholder is, the width of the UITextField's intrinsicContentSize will never drop below it. So if the placeholder's width is 130, and I begin to type, the text view's width will remain at 130 until what I am typing reaches a width greater than 130; after this the text view will grow.

I think you'll have to use a UITextField subclass where you get to set the instrinsicContentSize, overriding the default behavior of the intrinsicContentSize method which is evidently to size based on the placeholder.



来源:https://stackoverflow.com/questions/22106426/resize-uitextfield-horizontally-with-text-using-auto-layout

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