如何在只有单行的情况下调整UITextView的大小来自多行视图

时间:2017-01-18 05:46:47

标签: ios objective-c uitextview

我使用View制作了一个UITextview自定义控件。它工作正常。 当我输入新行时,文本视图会随着视图(深蓝色)而增加。此TextViell将以滚动的形式工作。

代码是

-(void)setTextViewHeight
{
    self.oldFrameHeight = self.commentTextView.frame.size.height;
    CGFloat fixedWidth = self.commentTextView.frame.size.width;
    CGSize newSize = [self.commentTextView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = self.commentTextView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    self.commentTextView.frame = newFrame;
    self.newFrameHeight = newFrame.size.height;
    NSLog(@"Old Frame %f",self.oldFrameHeight);
    NSLog(@"New Frame %f",self.newFrameHeight);
}
- (void)textViewDidChange:(UITextView *)textView
{


    self.oldFrameHeight = textView.frame.size.height;


    if(!(self.oldFrameHeight >= 44))
    {
        [self setTextViewHeight];

        if (self.newFrameHeight  > self.oldFrameHeight)
        {
            [self sabViewFrameChange];
        }
    }
    else if ([textView.text isEqualToString:@""])
    {
        [self.commentTextView setFrame:CGRectMake(60, 10,self.frame.size.width - 130, 30)];

        UIViewController *controller=(UIViewController *)self.delegate;
        self.frame =  CGRectMake(0,controller.view.frame.size.height - 50, controller.view.frame.size.width,50);
        self.height = 50;
    }
    else
    {
        self.commentTextView.scrollEnabled = YES;
    }
}

我的问题是

当我从UITextView中删除第二行时,大小将保持原样,我没有用行减少。

请帮帮我。 提前谢谢。

图片是

1)超过两行

enter image description here

2)单行

enter image description here

我该如何解决?有人有任何想法吗?

1 个答案:

答案 0 :(得分:1)

声明numLinesInTextView变量

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
    NSLog(@"%@",text);
    if ([text isEqualToString:@"\n"]) {
          NSLog(@"New line");
    }else{
        int numLines = [textView intrinsicContentSize].height / textView.font.lineHeight;
        NSLog(@"%f",textView.font.lineHeight);

        numLinesInTextView = numLines;
        if (numLinesInTextView == 0) {
            [self.commentTextView setFrame:CGRectMake(60, 10,self.frame.size.width - 130, 30)];
            UIViewController *controller=(UIViewController *)self.delegate;
            self.frame =  CGRectMake(0,controller.view.frame.size.height - 50, controller.view.frame.size.width,50);
            height = 50;
            numLinesInTextView = 0;
        }

    }
    return YES;
}

在项目中添加此方法并检查它是否完全正常工作。现在

快乐编码。