【问题标题】:Make UIToolbar resize with resizing UITextView contained in toolbar通过调整工具栏中包含的 UITextView 的大小来调整 UIToolbar 的大小
【发布时间】:2015-09-03 10:06:38
【问题描述】:

我有一个 UIToolbar,它位于 ViewController 的底部,并随着键盘向上滑动而移动到键盘的顶部。换句话说,它随着键盘移动。现在,我正在为工具栏中的 UITextView 创建一种方法,以便在用户在 textView 中键入换行符时调整其高度。到目前为止,我在课堂上使用此代码:

- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGFloat fixedWidthToolbar = self.navigationController.toolbar.frame.size.width;

    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGSize newSizeToolbar = [self.navigationController.toolbar sizeThatFits:CGSizeMake(fixedWidthToolbar, MAXFLOAT)];

    CGRect newFrame = textView.frame;
    CGRect newToolbarFrame = self.navigationController.toolbar.frame;

    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    newToolbarFrame.size = CGSizeMake(fmaxf(newSizeToolbar.width, fixedWidthToolbar), newSizeToolbar.height);
    textView.frame = newFrame;
    self.navigationController.toolbar.frame = newToolbarFrame;
}

除工具栏外,一切正常。通过工作,我的意思是 UITextView 每当添加换行符时都会增长(用户输入大量文本)。这里的问题是我没有看到工具栏像 textView 那样变大。我相信我的问题是我使用相同的代码来调整我用来调整 textview 大小的工具栏。

编辑: 这里的总体思路是允许 UITextView 和 UIToolbar 同时调整大小,允许用户看到 UITextView 中写入的文本。

我可以做些什么来实现这个目标?我做错了什么?

【问题讨论】:

    标签: ios uitoolbar


    【解决方案1】:

    您必须计算 textView 中的行数并为每个更改/行增量触发 frameUpdate,这已在 here 中讨论过

    然后您需要同时更新框架并根据更改再次计算它..

    关于行更新,您的代码可能如下所示:

    NSInteger linesPrevious = 0;//global variable to monitor changes
    
    - (void)textViewDidChange:(UITextView *)textView
    {
        [self checkNumberOfLines:YourTextView.text];
    }
    
    - (void)checkNumberOfLines:(UITextView *)textView
    {
        //compute the number of lines
        NSInteger linesNew = textView.contentSize.height/textView.font.lineHeight;
    
        if (linesNew != linesPrevious)
        {
            // make updates here
        }
    }
    

    我建议你先计算textView.frame,根据当前的contentSize,然后是UIToolbar.Frame

    并且不要忘记更新.origin.y 或您的工具栏以将其保持在正确的位置,假设您的工具栏的高度为44px,您需要将超出部分减去.origin.y 类似:

    frame = YourToolBar.frame;
    // example you updated the height with `64px`
    frame.size.height = 64;
    
    // you also need to update the `.origin.y`
    frame.origin.y -= (frame.size.height/*new*/ - YourToolBar.frame.size.height/*current*/);
    

    另外,如果您使用NSNotificationCenter 来更新您的工具栏的框架.. 您需要将原始帧存储在keyboardHideEvent 的全局变量中,这样您就可以轻松地将帧恢复到其原始位置..


    希望这对您有所帮助,干杯! ;)

    【讨论】:

    • 看来我正在以正确的方式调整 textView 的大小......所以我应该能够将工具栏的大小调整添加到您提供的这些方法中并离开textView 在 textViewDidChange 方法中更新。我希望这行得通,现在就实施。
    • 它会起作用的..(手指交叉)哈哈..祝你好运,编码快乐.. :)
    猜你喜欢
    • 2010-10-18
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2013-10-09
    • 2014-01-10
    • 2012-03-22
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多