【问题标题】:UITextView setContentSize does not work?UITextView setContentSize 不起作用?
【发布时间】:2014-11-17 08:57:53
【问题描述】:

我想改变我的 UITextView 的内容大小,我尝试如下:

[self.textView setContentSize:CGSizeMake(self.textView.contentSize.width, self.textView.contentSize.height+30)];

我发现它不起作用。更重要的是,我把它放在一个按钮的点击事件中,看看会发生什么。

- (IBAction)click:(id)sender {
    static int y = 0;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, y, 30, 30)];
    label.text = @"hello";
    y = y+30;
    [self.textView setContentSize:CGSizeMake(self.textView.contentSize.width, self.textView.contentSize.height+30)];
    NSLog(@"%f",self.textView.contentSize.height);
    [self.textView addSubview:label];
}

结果是setContentSize 不起作用?更重要的是,contentSize 只是随着文本内容的变化而变化。

我想知道为什么,有什么方法可以手动更改 UITextView 的 contentSize 吗?

添加:点击操作的输出

2014-11-17 17:05:56.306 viewControllerAdvance[2371:607] 82.000000 
2014-11-17 17:05:56.455 viewControllerAdvance[2371:607] 82.000000
2014-11-17 17:05:56.638 viewControllerAdvance[2371:607] 82.000000
2014-11-17 17:05:56.772 viewControllerAdvance[2371:607] 82.000000
2014-11-17 17:05:56.923 viewControllerAdvance[2371:607] 82.000000
2014-11-17 17:05:57.072 viewControllerAdvance[2371:607] 82.000000

【问题讨论】:

  • 能否请您发布您的 NSLog(@"%f",self.textView.contentSize.height);调用后的值 - (IBAction)click:(id)sender 方法几次?
  • 你确定需要设置contentsize还是frame
  • 当您在 textview 中写入文本时,contentsize 会自动增加,为什么您需要手动设置它??
  • @RameshMuthe,实际上,我想将一些内容词更改为标签(可能使用 UILabel),就像 StackOverFlow 的添加标签一样。所以也许文本视图的高度不是内容词的高度。
  • 只是做一次交叉检查你是在重置内容大小还是重新分配文本视图

标签: ios objective-c uitextview contentsize


【解决方案1】:

尝试像下面这样修改您的方法并检查它是否满足您的要求。要使用以下方式,您需要在滚动视图上添加文本视图,并且每当您增加文本视图的高度时,您都应该增加滚动视图的内容大小

- (IBAction)click:(id)sender { 

     static int y = 0;
     UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, y, 30, 30)];
     label.text = @"hello";
     y = y+30;
     [self.textView addSubview:label];

     CGFloat fixedWidth = textView.frame.size.width;
     CGFloat dynamicHeight = textView.frame.size.height+30;

     CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, dynamicHeight)];
     CGRect newFrame = textView.frame;
     newFrame.size = CGSizeMake(fixedWidth, fmaxf(newSize.height, dynamicHeight));
     textView.frame = newFrame;

 }

同时设置 textview.scrollEnabled = NO;

【讨论】:

  • 是的,确实符合我的要求!非常感谢!!但是为什么setContentSize 不起作用?
  • 看看这个stackoverflow.com/questions/19837178/… 似乎设置内容大小在 iOS 7 中可能不起作用
猜你喜欢
  • 2013-12-30
  • 1970-01-01
  • 1970-01-01
  • 2018-05-06
  • 2014-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多