iOS删除UITextView内容下方的额外空间

时间:2016-07-20 16:55:05

标签: ios objective-c uitextview

我在故事板视图控制器中有一个UITextView和Autolayout ON。我想根据UITextView的文本动态增加其高度。我可以增加它的大小,但文本下面有额外的空间。如何删除这个额外空间?

我试过这些代码:

[_descriptionText setText:string]; 
CGSize sizeThatFitsTextView = [_descriptionText sizeThatFits:CGSizeMake(_descriptionText.frame.size.width, MAXFLOAT)]
_descriptionTextHeight.constant = sizeThatFitsTextView.height;

此处_descriptionTextUITextView_descriptionTextHeight是一个高度限制,我用它来调整UITextView的大小。

我也试过这些代码:

[_descriptionText setText:string];
_descriptionTextHeight.constant = [_descriptionText intrinsicContentSize].height;

我能够删除多余的空间,但UITextView的大小没有增加。 我想在这里添加一点,我不想启用滚动。

enter image description here

3 个答案:

答案 0 :(得分:0)

试试这个,一定能为你效劳。

CGSize sizeThatFitsTextView = [txt sizeThatFits:CGSizeMake(txt.frame.size.width, MAXFLOAT)];

_descriptionText.contentOffset = CGPointZero;
_descriptionText.contentInset = UIEdgeInsetsMake(-6,0,0,0);
[txt layoutIfNeeded]; //added

NSLayoutConstraint *heightConstraint;
for (NSLayoutConstraint *constraint in _descriptionText.constraints) {
    if (constraint.firstAttribute == NSLayoutAttributeHeight) {
        heightConstraint = constraint;
        break;
    }
}
heightConstraint.constant = sizeThatFitsTextView.height-12;


[_descriptionText layoutIfNeeded];

答案 1 :(得分:0)

我不知道你为什么遇到这个困难。以下代码适用于我:

func adjustHeight(_ tv:UITextView) {
    self.heightConstraint.constant = ceil(tv.contentSize.height)
}

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    self.adjustHeight(textView)
    return true
}

答案 2 :(得分:0)

创建UITextView的子类并添加以下代码:

- (void)layoutSubviews
{
    [super layoutSubviews];

    // Layout subviews gets called when the text view's text changes in a way that might
    // require scrolling.   We get its new intrinsic size and update the height constraint
    // to grow the text view.
    CGSize intrinsicSize = self.intrinsicContentSize;
    self.heightConstraint.constant = MAX(intrinsicSize.height, self.minimumHeight);

    // The text view has a tendency to scroll up once it's full, but before the
    // height constraint that increases its height takes effect.   This results
    // in a blank area at the bottom, with the first line pushed out of view.
    // We cancel the scroll action, but only if it has not reached its maximum height.
    if (intrinsicSize.height < self.maximumHeight) {
        self.contentOffset = CGPointMake(0, 0);
    }
}

您还需要创建这些属性。它们控制文本视图的高度,并设置它的短小和高度限制。

/**
 The height constraint for the text view installed in the text view's superview.
 */
@property (weak,nonatomic) NSLayoutConstraint *heightConstraint;

/**
 The text view's minimum height.
 */
@property (nonatomic) CGFloat minimumHeight;

/**
 The text view's maximum height.
 */
@property (nonatomic) CGFloat maximumHeight;

像往常一样将文本视图添加到视图层次结构中,为文本视图的高度创建约束,并设置其最小和最大高度属性,然后全部设置。