如何增加包含文本视图的工具栏的大小



如何根据文本视图增加工具栏的大小,单击返回后,它应该移动到新行。在 uitextview 中输入文本时,工具栏的长度应增加

 text view which is in toolbar 
my code is  below  
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 10, 200, 42)];
    textView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:textView];
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320.f, 80.f)];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonItemStylePlain target:self action:@selector(close)];
    toolbar.items = [NSArray arrayWithObjects:doneButton,barItem,nil];
    textView.inputAccessoryView=toolbar;
    textView.delegate=self;
    [self.view addSubview:toolbar];
}

添加此代码。它并不完美,需要改进,但中心思想就是这样

- (void)textViewDidChange:(UITextView *)textView
{
    UIToolbar *toolbar = textView.superview; // you should use your stored property or instance variable here
    CGRect textViewFrame = textView.frame;
    textViewFrame.size.height = textView.contentSize.height;
    textView.frame = textViewFrame;
    textViewFrame.size.height += 40.0f; // the text view padding
    toolbar.frame = textViewFrame;
}

viewDidLoad 中没有正确的视图框架/大小。您应该在 viewDidLayoutSubviews 中调整大小。在这里阅读更多内容:

如果使用自动布局,请为刚创建的每个视图分配足够的约束,以控制视图的位置和大小 视图。否则,实现 viewWillLayoutSubviews 和 viewDidLayoutSubviews 方法,用于调整子视图的框架 视图层次结构。请参阅"调整视图控制器视图的大小"。

由于textView使用ScrollView,因此检查contentSize似乎是执行所需操作的简单方法。
所以。。。为了简化斯托罗伊的例子:

- (void)textViewDidChange:(UITextView *)textView
{
    float newHeight = textView.contentSize.height;
    if(newHeight < 80){
    }
    else if (newHeight < self.view.frame.size.height){
        [toolbar setFrame:CGRectMake(0, 0, 320, newHeight)];
        [textView setFrame:CGRectMake(100, 10, 200, newHeight-40)];
    }
}

笔记:

  • UIToolbar *toolbar;(在类的 .h 文件中声明)
  • 这些是特定于您的示例的硬编码值,因此请根据您的要求对其进行优化
  • (newHeight <80) -- 其中 80 是工具栏的初始或最小高度
  • (newHeight
  • ) -- 其中 self.view.frame.size.height 为您提供整个视图的高度,并防止将子视图帧增加到视图边界之外。

不完美,但从这里开始。

最新更新