简体   繁体   English

根据iOS中的文本宽度动态更改文本视图宽度

[英]Change the text view width dynamically based on the text width in iOS

I have created and added a text field to a view as below 我已经创建了一个文本字段并将其添加到视图中,如下所示

CGRect frame = CGRectMake(20, 100, 280, 20);
UITextField *utf = [[UITextField alloc] initWithFrame:frame];
...
[scrollView addSubview:itemBrand];

Suppose the text on text view is abcdefghijklmno and the width is 100. 假设文本视图上的文本为abcdefghijklmno,宽度为100。

How can I change the with of the text view to 100 instead of 280 dynamically? 如何将文本视图的with动态更改为100,而不是280?

Thanks 谢谢

You can ask the size of your text using this function: 您可以使用以下功能询问文本的大小:

CGSize textSize = [inputText sizeWithFont:font 
                               constrainedToSize:maximumLabelSize 
                                   lineBreakMode:UILineBreakModeWordWrap];

inputText being the text you want to ask the size of. inputText是您要询问其大小的文本。

font being the font you are using for the text. font是您用于文本的字体。

maximumLabelSize being the maximum size your text is allowed to be. maximumLabelSize是允许的文本最大大小。

After this you can comform your textfield to this size. 之后,您可以将文本字段调整为该大小。

Copy the frame over so you can modify if (doing utf.frame.size.width = something, won't work) 复制框架,以便您可以修改是否(做utf.frame.size.width =某事,将不起作用)

CGRect f = utf.frame;
f.size.width = yourNewWidth;
utf.frame = f;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM