2
textViewBusiness = [[UITextView alloc] initWithFrame:CGRectMake(25,332,268,60)];
textViewBusiness.text=strMyBusiness;
textViewBusiness.editable=NO;
textViewBusiness.font = [UIFont fontWithName:@"Arial" size: 17.0];
textViewBusiness.layer.borderWidth = 2.0f;
textViewBusiness.layer.borderColor = [[UIColor grayColor] CGColor];
textViewBusiness.backgroundColor = [UIColor clearColor];
[textViewBusiness setTextColor:[UIColor blackColor]];
[self.scrollView addSubview: textViewBusiness];

CGRect frame = textViewBusiness.frame;
frame.size.height = textViewBusiness.contentSize.height;
textViewBusiness.frame = frame;

随着内容的增加,我想增加文本字段的大小....

这段代码对我不起作用...

谢谢

4

3 回答 3

2

您无需考虑UITextView显示不可编辑的文本。除此之外,您可以使用 UILabel 并且可以在运行时找出标签的高度。每次内容的大小不同,设置UILabel相应的框架。

使用它在运行时找出标签的高度

- (CGFloat) heightOfTextLabel:(NSString *) contentText
{
    CGSize constraint = CGSizeMake(268,4000);

    CGSize size = [contentText sizeWithFont:[UIFont fontWithName:@"Arial" size: 17.0] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

     return size.height;       
}

此方法每次都会为您返回可变高度的内容。

现在将此高度设置为您的UILabel

CGFloat heightOfLabel = [self heightOfTextLabel:strMyBusiness];

UILabel* textToShowLabel = [[UILabel alloc] initWithFrame:CGRectMake(25,332,268,heightOfLabel)];

textToShowLabel.text=strMyBusiness;

textToShowLabel.font = [UIFont fontWithName:@"Arial" size: 17.0];

textToShowLabel.layer.borderWidth = 2.0f;

textToShowLabel.layer.borderColor = [[UIColor grayColor] CGColor];

textToShowLabel.backgroundColor = [UIColor clearColor];

[textToShowLabel setTextColor:[UIColor blackColor]];

[self.scrollView addSubview: textToShowLabel];
于 2012-07-16T13:03:57.893 回答
0

GrowingTextView是一个可重复使用的 iOS 组件,可以满足您的需求,您可以在 GitHub 上找到

我希望这有帮助。

于 2012-07-16T12:27:59.040 回答
0

您需要将代码分成 2 个片段,然后将它们放在适当的位置,然后您的代码应该可以工作。

片段 1(在我的测试中,我将此片段放在 viewDidLoad 中):

textViewBusiness = [[UITextView alloc] initWithFrame:CGRectMake(25,332,268,60)];
textViewBusiness.text=strMyBusiness;
textViewBusiness.editable=NO;
textViewBusiness.font = [UIFont fontWithName:@"Arial" size: 17.0];
textViewBusiness.layer.borderWidth = 2.0f;
textViewBusiness.layer.borderColor = [[UIColor grayColor] CGColor];
textViewBusiness.backgroundColor = [UIColor clearColor];
[textViewBusiness setTextColor:[UIColor blackColor]];
[self.scrollView addSubview: textViewBusiness];

确保上面的片段运行,并且您的文本视图显示在屏幕中,然后运行第二个片段。如果你的文本视图没有显示在屏幕上,那么 contentView 没有被初始化,并且高度是未定义的。

片段 2(在我的测试中,我将此片段放入viewDidAppear):

CGRect frame = textViewBusiness.frame;
frame.size.height = textViewBusiness.contentSize.height;
textViewBusiness.frame = frame;

祝你好运!

于 2012-07-16T12:28:09.337 回答