如何将UITextView的大小调整为其内容?

时间:2008-09-08 19:21:20

标签: ios cocoa-touch autolayout uikit uitextview

有没有一种方法可以调整UITextView的大小以符合其内容?比方说我有UITextView,其中包含一行文字:

"Hello world"

然后我添加另一行文字:

"Goodbye world"

在Cocoa Touch中是否有一个很好的方法来获取将保存文本视图中所有行的rect,以便我可以相应地调整父视图?

作为另一个示例,请查看日历应用程序中事件的注释字段 - 注意单元格(及其包含的UITextView)如何扩展以包含注释字符串中的所有文本行。

41 个答案:

答案 0 :(得分:583)

适用于iOS 6.1和iOS 7:

- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    textView.frame = newFrame;
}

或者在Swift中(与iOS 11中的Swift 4.1一起使用)

let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

如果您想要支持iOS 6.1,那么您还应该:

textview.scrollEnabled = NO;

答案 1 :(得分:575)

这不再适用于iOS 7或更高版本

实际上有一种非常简单的方法可以将UITextView的大小调整为正确的内容高度。可以使用UITextView contentSize来完成。

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

需要注意的一点是,正确的contentSize仅在 UITextView添加到addSubview的视图后才可用。在此之前,它等于frame.size

如果自动布局为ON,则无效。使用自动布局时,一般方法是使用sizeThatFits方法并更新高度约束上的constant值。

CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.frame.size];
heightConstraint.constant = sizeThatShouldFitTheContent.height;

heightConstraint是一种布局约束,您通常通过将属性链接到故事板中创建的高度约束来通过IBOutlet进行设置。


只是为了增加这个惊人的答案,2014年,如果你:

[self.textView sizeToFit];

仅与 iPhone6 + 的行为存在差异:

enter image description here

只有6+(不是5s或6),它确实为UITextView增加了“一个空行”。 “RL解决方案”完美地解决了这个问题:

CGRect _f = self.mainPostText.frame;
_f.size.height = self.mainPostText.contentSize.height;
self.mainPostText.frame = _f;

它修复了6 +上的“额外线”问题。

答案 2 :(得分:88)

要在UITextView内动态调整大小UITableViewCell,我发现以下组合在Xcode 6中与iOS 8 SDK一起使用:

  • UITextView添加到UITableViewCell并将其约束到两侧
  • UITextView的{​​{1}}媒体资源设为scrollEnabled。启用滚动后,NO的框架与其内容大小无关,但在禁用滚动的情况下,两者之间存在关系。
  • 如果您的表使用原始默认行高44,那么它将自动计算行高,但如果您将默认行高更改为其他行,则可能需要手动启用行的自动计算UITextView中的高度:

    viewDidLoad

对于只读动态调整tableView.estimatedRowHeight = 150; tableView.rowHeight = UITableViewAutomaticDimension; 的大小,就是这样。如果您允许用户编辑UITextView中的文字,您还需要:

  • 实施UITextView协议的textViewDidChange:方法,并在每次编辑文本时告诉UITextViewDelegate重绘自己:

    tableView
  • 不要忘记在- (void)textViewDidChange:(UITextView *)textView; { [tableView beginUpdates]; [tableView endUpdates]; } UITextView

  • 中设置Storyboard代理人

答案 3 :(得分:57)

斯威夫特:

textView.sizeToFit()

答案 4 :(得分:55)

使用代码和故事板的非常简单的工作解决方案。

按代码

textView.scrollEnabled = false

按故事板

取消选中滚动启用

enter image description here

除此之外无需做任何事情。

答案 5 :(得分:24)

在我(有限)的经历中,

- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode

不尊重换行符,因此您最终可能会比实际需要更短CGSize

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

似乎确实尊重换行符。

此外,文本实际上并未呈现在UITextView的顶部。在我的代码中,我将UITextView的新高度设置为比sizeOfFont方法返回的高度大24个像素。

答案 6 :(得分:22)

在iOS6中,您可以在设置文本后立即检查UITextView的contentSize属性。在iOS7中,这将不再有效。如果要为iOS7恢复此行为,请将以下代码放在UITextView的子类中。

- (void)setText:(NSString *)text
{
    [super setText:text];

    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        CGRect rect = [self.textContainer.layoutManager usedRectForTextContainer:self.textContainer];
        UIEdgeInsets inset = self.textContainerInset;
        self.contentSize = UIEdgeInsetsInsetRect(rect, inset).size;
    }
}

答案 7 :(得分:18)

我会在页面底部发布正确的解决方案,以防有人勇敢(或绝望)阅读到这一点。

以下是那些不想阅读所有文字的人的gitHub回购:resizableTextView

这适用于iOs7(我相信它可以与iOs8配合使用)和自动布局。你不需要魔术数字,禁用布局等等。简洁优雅的解决方案。

我认为,所有与约束相关的代码都应该转到updateConstraints方法。所以,让我们自己制作ResizableTextView

我们在这里遇到的第一个问题是在viewDidLoad方法之前不知道真实的内容大小。我们可以采取漫长而错误的道路并根据字体大小,换行符等计算它。但我们需要强大的解决方案,所以我们会这样做:

CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];

所以现在我们知道真实的contentSize,无论我们身在何处:viewDidLoad之前或之后。现在在textView上添加高度约束(通过故事板或代码,无论如何)。我们将使用contentSize.height

调整该值
[self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
    if (constraint.firstAttribute == NSLayoutAttributeHeight) {
        constraint.constant = contentSize.height;
        *stop = YES;
    }
}];

最后要做的是告诉超类updateConstraints

[super updateConstraints];

现在我们的班级看起来像:

<强> ResizableTextView.m

- (void) updateConstraints {
    CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];

    [self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
        if (constraint.firstAttribute == NSLayoutAttributeHeight) {
            constraint.constant = contentSize.height;
            *stop = YES;
        }
    }];

    [super updateConstraints];
}

漂亮干净吧?而且您不必在控制器中处理该代码!

但等等! Y no ANIMATION!

您可以轻松设置更改动画,以使textView平滑。这是一个例子:

    [self.view layoutIfNeeded];
    // do your own text change here.
    self.infoTextView.text = [NSString stringWithFormat:@"%@, %@", self.infoTextView.text, self.infoTextView.text];
    [self.infoTextView setNeedsUpdateConstraints];
    [self.infoTextView updateConstraintsIfNeeded];
    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
        [self.view layoutIfNeeded];
    } completion:nil];

答案 8 :(得分:12)

你试过[textView sizeThatFits:textView.bounds]吗?

编辑:sizeThatFits返回大小但实际上并未调整组件大小。我不确定这是否是您想要的,或者[textView sizeToFit]是否更符合您的要求。在任何一种情况下,我都不知道它是否完全适合您想要的内容,但这是第一个尝试的内容。

答案 9 :(得分:9)

另一种方法是使用NSString方法查找特定字符串占用的大小:

-(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

这将返回适合给定字符串的矩形的大小。传递具有所需宽度和最大高度的大小,然后您可以查看返回的高度以适合文本。有一个版本可以让你指定换行模式。

然后,您可以使用返回的尺寸更改视图的大小以适应。

答案 10 :(得分:8)

如果您没有UITextView方便(例如,您正在调整表格视图单元格),则必须通过测量字符串来计算大小,然后计算8磅的填充在UITextView的每一边。例如,如果您知道文本视图所需的宽度并想要计算出相应的高度:

NSString * string = ...;
CGFloat textViewWidth = ...;
UIFont * font = ...;

CGSize size = CGSizeMake(textViewWidth - 8 - 8, 100000);
size.height = [string sizeWithFont:font constrainedToSize:size].height + 8 + 8;

这里,每个8占据了四个填充边缘中的一个,而100000只是一个非常大的最大尺寸。

在实践中,您可能希望在高度上添加额外的font.leading;这会在文本下方添加一个空白行,如果文本视图正下方有视觉上很重的控件,则可能看起来更好。

答案 11 :(得分:7)

我们可以通过约束来实现。

  1. 为UITextView设置高度约束。 enter image description here
  2. 2.为该高度约束创建IBOutlet。

     @property (weak, nonatomic) IBOutlet NSLayoutConstraint *txtheightconstraints;
    

    3.忘记为你的textview设置委托。

    4

    -(void)textViewDidChange:(UITextView *)textView
    {
        CGFloat fixedWidth = textView.frame.size.width;
        CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
        CGRect newFrame = textView.frame;
        newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
        NSLog(@"this is updating height%@",NSStringFromCGSize(newFrame.size));
        [UIView animateWithDuration:0.2 animations:^{
                      _txtheightconstraints.constant=newFrame.size.height;
        }];
    
    }
    

    然后像这样更新你的约束:)

答案 12 :(得分:7)

以下内容已足够:

  1. 请记住为UITextView 设置滚动启用
  2. enter image description here

    1. 正确设置自动布局约束。
    2. 您甚至可以使用UITableViewAutomaticDimension

答案 13 :(得分:6)

我找到了一种方法来根据文本字段中的文本调整文本字段的高度,并根据文本字段的高度在其下方排列标签!这是代码。

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;

[self.view addSubview:_textView];
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 5 + frame.origin.y + frame.size.height, 300, 20)];
lbl.text = @"Hello!";
[self.view addSubview:lbl];

答案 14 :(得分:6)

结合Mike McMaster的回答,您可能希望做类似的事情:

[myTextView setDelegate: self];

...

- (void)textViewDidChange:(UITextView *)textView {
  if (myTextView == textView) {
     // it changed.  Do resizing here.
  }
}

答案 15 :(得分:6)

从iOS 8开始,可以使用UITableView的自动布局功能自动调整UITextView的大小,而根本不需要自定义代码。我在github中放了一个项目来演示这个实际操作,但这里有关键:

  1. UITextView必须禁用滚动,您可以通过编程方式或通过界面构建​​器执行此操作。如果启用滚动,则不会调整大小,因为滚动可让您查看更大的内容。
  2. 在UITableViewController的viewDidLoad中,您必须为estimatedRowHeight设置一个值,然后将rowHeight设置为UITableViewAutomaticDimension
  3. 
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.tableView.estimatedRowHeight = self.tableView.rowHeight;
        self.tableView.rowHeight = UITableViewAutomaticDimension;
    }
    
    1. 项目部署目标必须是iOS 8或更高版本。

答案 16 :(得分:6)

使用自动布局和你的sizetofit的人不起作用,请检查你的宽度约束一次。如果您错过了宽度约束,那么高度将是准确的。

无需使用任何其他API。只需一行即可解决所有问题。

[_textView sizeToFit];

在这里,我只关心高度,保持宽度固定,并错过了故事板中TextView的宽度约束。

这是为了显示服务中的动态内容。

希望这可能有所帮助..

答案 17 :(得分:4)

我查看了所有答案,并且都保持固定宽度并仅调整高度。如果你想调整宽度,你可以很容易地使用这种方法:

所以在配置文本视图时,请设置滚动禁用

textView.isScrollEnabled = false

然后在委托方法func textViewDidChange(_ textView: UITextView)中添加以下代码:

func textViewDidChange(_ textView: UITextView) {
    let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
    textView.frame = CGRect(origin: textView.frame.origin, size: newSize)
}

输出:

enter image description here

enter image description here

答案 18 :(得分:4)

禁用滚动

添加constaints

并添加您的文字

[yourTextView setText:@"your text"];
[yourTextView layoutIfNeeded];

如果你使用UIScrollView,你也应该添加它;

[yourScrollView layoutIfNeeded];

-(void)viewDidAppear:(BOOL)animated{
    CGRect contentRect = CGRectZero;

    for (UIView *view in self.yourScrollView.subviews) {
         contentRect = CGRectUnion(contentRect, view.frame);
    }
    self.yourScrollView.contentSize = contentRect.size;
}

答案 19 :(得分:4)

使用UITextViewDelegate是最简单的方法:

func textViewDidChange(_ textView: UITextView) {
    textView.sizeToFit()
    textviewHeight.constant = textView.contentSize.height
}

答案 20 :(得分:4)

这是@jhibberd的快速版本

    let cell:MsgTableViewCell! = self.tableView.dequeueReusableCellWithIdentifier("MsgTableViewCell", forIndexPath: indexPath) as? MsgTableViewCell
    cell.msgText.text = self.items[indexPath.row]
    var fixedWidth:CGFloat = cell.msgText.frame.size.width
    var size:CGSize = CGSize(width: fixedWidth,height: CGFloat.max)
    var newSize:CGSize = cell.msgText.sizeThatFits(size)
    var newFrame:CGRect = cell.msgText.frame;
    newFrame.size = CGSizeMake(CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), newSize.height);
    cell.msgText.frame = newFrame
    cell.msgText.frame.size = newSize        
    return cell

答案 21 :(得分:4)

当我需要在适合特定区域的UITextView中创建文本时,这很有效:

// The text must already be added to the subview, or contentviewsize will be wrong.

- (void) reduceFontToFit: (UITextView *)tv {
    UIFont *font = tv.font;
    double pointSize = font.pointSize;

    while (tv.contentSize.height > tv.frame.size.height && pointSize > 7.0) {
        pointSize -= 1.0;
        UIFont *newFont = [UIFont fontWithName:font.fontName size:pointSize];
        tv.font = newFont;
    }
    if (pointSize != font.pointSize)
        NSLog(@"font down to %.1f from %.1f", pointSize, tv.font.pointSize);
}

答案 22 :(得分:3)

对于iOS 7.0,不要将frame.size.height设置为contentSize.height(目前无效),请使用[textView sizeToFit]

请参阅this question

答案 23 :(得分:1)

根据Nikita Took的回答,我在Swift中找到了以下解决方案,该解决方案适用于带有自动布局的iOS 8:

    descriptionTxt.scrollEnabled = false
    descriptionTxt.text = yourText

    var contentSize = descriptionTxt.sizeThatFits(CGSizeMake(descriptionTxt.frame.size.width, CGFloat.max))
    for c in descriptionTxt.constraints() {
        if c.isKindOfClass(NSLayoutConstraint) {
            var constraint = c as! NSLayoutConstraint
            if constraint.firstAttribute == NSLayoutAttribute.Height {
                constraint.constant = contentSize.height
                break
            }
        }
    }

答案 24 :(得分:1)

希望这会有所帮助:

- (void)textViewDidChange:(UITextView *)textView {
  CGSize textSize = textview.contentSize;
  if (textSize != textView.frame.size)
      textView.frame.size = textSize;
}

答案 25 :(得分:1)

如果有其他人到这里,这个解决方案适合我,1“Ronnie Liew”+4“user63934”(我的文字来自网络服务):   注意1000(在我的情况下,没有什么可以这么大)

UIFont *fontNormal = [UIFont fontWithName:FONTNAME size:FONTSIZE];

NSString *dealDescription = [client objectForKey:@"description"];

//4
CGSize textSize = [dealDescription sizeWithFont:fontNormal constrainedToSize:CGSizeMake(containerUIView.frame.size.width, 1000)];

CGRect dealDescRect = CGRectMake(10, 300, containerUIView.frame.size.width, textSize.height);

UITextView *dealDesc = [[[UITextView alloc] initWithFrame:dealDescRect] autorelease];

dealDesc.text = dealDescription;
//add the subview to the container
[containerUIView addSubview:dealDesc];

//1) after adding the view
CGRect frame = dealDesc.frame;
frame.size.height = dealDesc.contentSize.height;
dealDesc.frame = frame;

那就是......干杯

答案 26 :(得分:1)

就像ios 11上的魅力一样 我正在一个小区工作,就像一个带泡泡的聊天室。

let content = UITextView(frame: CGRect(x: 4, y: 4, width: 0, height: 0))
content.text = "what ever short or long text you wanna try"
content.textAlignment = NSTextAlignment.left
content.font = UIFont.systemFont(ofSize: 13)
let spaceAvailable = 200 //My cell is fancy I have to calculate it...
let newSize = content.sizeThatFits(CGSize(width: CGFloat(spaceAvailable), height: CGFloat.greatestFiniteMagnitude))
content.isEditable = false
content.dataDetectorTypes = UIDataDetectorTypes.all
content.isScrollEnabled = false
content.backgroundColor = UIColor.clear
bkgView.addSubview(content)

答案 27 :(得分:1)

如果您需要在textView

中动态调整tableViewCellstaticTableView,请回答以下问题

[https://stackoverflow.com/a/43137182/5360675][1]

答案 28 :(得分:1)

我发现根据文本大小重新调整UITextView高度的最佳方法。

CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@"SAMPLE_FONT" size:14.0]
                       constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX)];

或您可以使用

CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@"SAMPLE_FONT" size:14.0]
                       constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX) lineBreakMode:NSLineBreakByTruncatingTail];

答案 29 :(得分:1)

对于那些希望textview实际向上移动并保持底线位置的人

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

if(frame.size.height > textView.frame.size.height){
    CGFloat diff = frame.size.height - textView.frame.size.height;
    textView.frame = CGRectMake(0, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);
}
else if(frame.size.height < textView.frame.size.height){
    CGFloat diff = textView.frame.size.height - frame.size.height;
    textView.frame = CGRectMake(0, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);
}

答案 30 :(得分:1)

快速回答: 以下代码计算textView的高度。

                let maximumLabelSize = CGSize(width: Double(textView.frame.size.width-100.0), height: DBL_MAX)
                let options = NSStringDrawingOptions.TruncatesLastVisibleLine | NSStringDrawingOptions.UsesLineFragmentOrigin
                let attribute = [NSFontAttributeName: textView.font!]
                let str = NSString(string: message)
                let labelBounds = str.boundingRectWithSize(maximumLabelSize,
                    options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                    attributes: attribute,
                    context: nil)
                let myTextHeight = CGFloat(ceilf(Float(labelBounds.height)))

现在,您可以将textView的高度设置为myTextHeight

答案 31 :(得分:1)

唯一可行的代码是使用&#39; SizeToFit&#39;就像上面的jhibberd回答一样,但实际上除非你在 ViewDidAppear 中调用它或将其连接到UITextView文本更改事件,否则它不会被接收。

答案 32 :(得分:0)

如果您使用的是scrollview和内容视图,并且希望根据TextView内容高度增加高度,那么这段代码将对您有所帮助。

希望这会有所帮助,它在iOS9.2中完美运行

当然设置textview.scrollEnabled = NO;

-(void)adjustHeightOfTextView
{
    //this pieces of code will helps to adjust the height of the uitextview View W.R.T content
    //This block of code work will calculate the height of the textview text content height and calculate the height for the whole content of the view to be displayed.Height --> 400 is fixed,it will change if you change anything in the storybord.


CGSize textViewSize = [self.textview sizeThatFits:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];//calulcate the content width and height

float textviewContentheight =textViewSize.height;
self.scrollview.contentSize = CGSizeMake(self.textview.frame.size.width,textviewContentheight + 400);//height value is passed
self.scrollview.frame =CGRectMake(self.scrollview.frame.origin.x, self.scrollview.frame.origin.y, self.scrollview.frame.size.width, textviewContentheight+400);

CGRect Frame = self.contentview.frame;
Frame.size.height = textviewContentheight + 400;
[self.contentview setFrame:Frame];

self.textview.frame =CGRectMake(self.textview.frame.origin.x, self.textview.frame.origin.y, self.textview.frame.size.width, textviewContentheight);
[ self.textview setContentSize:CGSizeMake( self.textview.frame.size.width,textviewContentheight)];
self.contenview_heightConstraint.constant = 

self.scrollview.bounds.size.height;
    NSLog(@"%f",self.contenview_heightConstraint.constant);
}

答案 33 :(得分:0)

这种方法似乎适用于ios7

 // Code from apple developer forum - @Steve Krulewitz, @Mark Marszal, @Eric Silverberg
- (CGFloat)measureHeight
{
    if ([self respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)])
    {
    CGRect frame = internalTextView.bounds;
    CGSize fudgeFactor;
    // The padding added around the text on iOS6 and iOS7 is different.
    fudgeFactor = CGSizeMake(10.0, 16.0);

    frame.size.height -= fudgeFactor.height;
    frame.size.width -= fudgeFactor.width;

    NSMutableAttributedString* textToMeasure;
    if(internalTextView.attributedText && internalTextView.attributedText.length > 0){
        textToMeasure = [[NSMutableAttributedString alloc] initWithAttributedString:internalTextView.attributedText];
    }
    else{
        textToMeasure = [[NSMutableAttributedString alloc] initWithString:internalTextView.text];
        [textToMeasure addAttribute:NSFontAttributeName value:internalTextView.font range:NSMakeRange(0, textToMeasure.length)];
    }

    if ([textToMeasure.string hasSuffix:@"\n"])
    {
        [textToMeasure appendAttributedString:[[NSAttributedString alloc] initWithString:@"-" attributes:@{NSFontAttributeName: internalTextView.font}]];
    }

    // NSAttributedString class method: boundingRectWithSize:options:context is
    // available only on ios7.0 sdk.
    CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                              context:nil];

    return CGRectGetHeight(size) + fudgeFactor.height;
}
else
{
    return self.internalTextView.contentSize.height;
}
}

答案 34 :(得分:0)

询问UITextView的最简单方法就是调用-sizeToFit它也应该与scrollingEnabled = YES一起使用,然后检查高度并在文本视图上添加高度约束相同的价值 注意UITexView包含insets,这意味着你不能向字符串对象询问它想要使用多少空间,因为这只是文本的边界矩形。
所有使用-sizeToFit的尺寸错误的人可能是因为文本视图尚未布局到界面尺寸。
当您使用大小类和UITableView时,总是会发生这种情况,第一次在- tableView:cellForRowAtIndexPath:中创建单元格时,任何配置的大小都会出现,如果您刚才计算出值文本视图将具有与预期不同的宽度,这将拧紧所有尺寸 为了解决这个问题,我发现有必要覆盖单元格的-layoutSubviews方法来重新计算文本视图高度。

答案 35 :(得分:0)

使用键值观察(KVO)非常简单,只需创建UITextView的子类并执行以下操作即可:

private func setup() { // Called from init or somewhere

    fitToContentObservations = [
        textView.observe(\.contentSize) { _, _ in
            self.invalidateIntrinsicContentSize()
        },
        // For some reason the content offset sometimes is non zero even though the frame is the same size as the content size.
        textView.observe(\.contentOffset) { _, _ in
            if self.contentOffset != .zero { // Need to check this to stop infinite loop
                self.contentOffset = .zero
            }
        }
    ]
}
public override var intrinsicContentSize: CGSize {
    return contentSize
}

如果您不想继承子类,可以尝试在textView.bounds = textView.contentSize观察者中进行contentSize

答案 36 :(得分:0)

这对于 Swift 5 非常适用,以防用户想在用户即时编写文本后使它适合TextView。

只需使用以下方法实现 UITextViewDelegate

func textViewDidChange(_ textView: UITextView) {
    let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
    textView.frame.size = CGSize(width: newSize.width, height: newSize.height)
}

答案 37 :(得分:0)

对我有用的最简单的解决方案是在 Storyboard 中的 textView 上设置高度约束,然后将 textView 和高度约束连接到代码:

@IBOutlet var myAwesomeTextView: UITextView!
@IBOutlet var myAwesomeTextViewHeight: NSLayoutConstraint!

然后在设置文本和段落样式后,在viewDidAppear中添加:

self.myAwesomeTextViewHeight.constant = self.myAwesomeTextView.contentSize.height

一些注意事项:

  1. 与其他解决方案相比,isScrollEnabled 必须设置为 true 才能使其发挥作用。
  2. 就我而言,我在代码中为字体设置了自定义属性,因此我必须在 viewDidAppear 中设置高度(在此之前它无法正常工作)。如果您没有更改代码中的任何文本属性,您应该能够在设置文本后在 viewDidLoad 或任何地方设置高度。

答案 38 :(得分:0)

看起来这家伙为 NSTextView 找到了答案,他的回答也适用于 iOS。结果是 internalContentSize 不与布局管理器同步。如果布局发生在 internalContentSize 之后,您可能会出现差异。

他有一个简单的解决办法。

NSTextView in NSOutlineView with IntrinsicContentSize setting wrong height

答案 39 :(得分:-1)

这是步骤

解决方案适用于所有版本的iOS。 Swift 3.0及更高版本。

  1. 将您的UITextView添加到View中。我正在用代码添加它,您可以通过界面生成器添加。
  2. 添加约束。我在代码中添加了约束,您也可以在界面生成器中完成约束。
  3. 使用UITextViewDelegate方法func textViewDidChange(_ textView: UITextView)调整TextView的大小

代码:

  1. //1. Add your UITextView in ViewDidLoad
    let textView = UITextView()
    textView.frame = CGRect(x: 0, y: 0, width: 200, height: 100)
    textView.backgroundColor = .lightGray
    textView.text = "Here is some default text."
    
    
    
    //2. Add constraints
    textView.translatesAutoresizingMaskIntoConstraints = false
    [
    textView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
    textView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    textView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    textView.heightAnchor.constraint(equalToConstant: 50),
    textView.widthAnchor.constraint(equalToConstant: 30)
    ].forEach{ $0.isActive = true }
    
    textView.font = UIFont.preferredFont(forTextStyle: .headline)
    
    textView.delegate = self
    textView.isScrollEnabled = false
    
    textViewDidChange(textView)
    
    
    //3. Implement the delegate method.
    func textViewDidChange(_ textView: UITextView) {
    let size = CGSize(width: view.frame.width, height: .infinity)
    let estimatedSize = textView.sizeThatFits(size)
    
    textView.constraints.forEach { (constraint) in
        if constraint.firstAttribute == .height {
            print("Height: ", estimatedSize.height)
            constraint.constant = estimatedSize.height
        }
    }
    }
    

答案 40 :(得分:-3)

不确定为什么人们总是过于复杂化: 这是:

- (void)textViewDidChange:(UITextView *)textView{ CGRect frame = textView.frame;
CGFloat height = [self measureHeightOfUITextView:textView];
CGFloat insets = textView.textContainerInset.top + textView.textContainerInset.bottom;
height += insets;
frame.size.height = height;

if(frame.size.height > textView.frame.size.height){
    CGFloat diff = frame.size.height - textView.frame.size.height;
    textView.frame = CGRectMake(5, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);
}
else if(frame.size.height < textView.frame.size.height){
    CGFloat diff = textView.frame.size.height - frame.size.height;
    textView.frame = CGRectMake(5, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);
}
[textView setNeedsDisplay];
}