1

这是我尝试过的,

 UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 10)];
    NSString *str = @"This is a test text view to check the auto increment of height of a text     view. This is only a test. The real data is something different.";
    _textView.text = str;


CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;//Here i am adjusting the textview

[self.view addSubview:_textView];



Basically after fitting the text into textview,scrolling is enable,but i cannot view the content inside the textview without scrolling the textview.I do want to initialize the UITextView frame size based on the text size,font name etc.

任何解决方案表示赞赏。谢谢。

4

1 回答 1

2
NSString *str = @"This is a test text view to check the auto increment of height of a text     view. This is only a test. The real data is something different.";
UIFont * myFont = [UIFont fontWithName:@"your font Name"size:12];//specify your font details here

//然后计算上述文本所需的高度。

CGSize textviewSize = [str sizeWithFont:myFont constrainedToSize:CGSizeMake(300, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];

//根据你从上面得到的高度初始化你的textview

UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, textviewSize.width, textviewSize.height)];
_textView.text = str;
[self.view addSubview:_textView];

而且您还想禁用 textview 中的滚动,然后参考这个。

正如 William Jockusch 在他的回答中所说:

您可以通过将以下方法放入 UITextView 子类来禁用几乎所有滚动:

- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated {
  // do nothing
}

我说“几乎”所有滚动的原因是即使使用上述内容,它仍然接受用户滚动。尽管您可以通过将 self.scrollEnabled 设置为 NO 来禁用它们。

如果您只想禁用某些滚动,则制作一个 ivar,我们将其称为 acceptScrolls,以确定您是否要允许滚动。然后您的 scrollRectToVisible 方法可以如下所示:

- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated {
   if (self.acceptScrolls)
     [super scrollRectToVisible: rect animated: animated];
}
于 2013-01-26T05:09:40.387 回答