【问题标题】:How to prevent button moving to the right when changing toolbar height?更改工具栏高度时如何防止按钮向右移动?
【发布时间】:2017-08-31 16:41:06
【问题描述】:

我有一个带有GrowingTextView、一个固定空间和一个UIBarButtonItem 的UIToolbar。看起来像:

GrowingTextView library调整TextView的高度约束时,调整工具栏高度的同时也将按钮向右移动:

不管文本视图有多大和按钮的位置有多大。文本视图第一次调整大小时,它总是向右移动 20 像素。只有第一次。

我该如何解决?我尝试在可视模式下编写约束,但我无法以这种方式获得这种布局。我也尝试过刷新固定空间。

添加固定空格按钮的代码:

let item1 = UIBarButtonItem(customView: sendButton)
fixedSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
fixedSpace.width = UIApplication.shared.windows[0].frame.width - rightMargin - sendButton.frame.width
bottomToolbar.items = [fixedSpace, item1]

添加GrowingTextView的代码:

let views: [String: Any] = ["textView": messageToSendTextView]
let hConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-8-[textView]-60-|", options: [], metrics: nil, views: views)
let vConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-8-[textView]-8-|", options: [], metrics: nil, views: views)
bottomToolbar.addConstraints(hConstraints)
bottomToolbar.addConstraints(vConstraints)
self.view.layoutIfNeeded()

【问题讨论】:

  • 在视图出现后强制/触发布局会发生什么?
  • 在你的约束中:H:|-8-[textView]-60-|,你为什么没有任何按钮?我的意思是H:|-8-[textView]-10-[button]-60-|
  • @Honey 我试过了,但显然不是这样。这样,您将获得 this(无文本视图)
  • @meaning-matters 抱歉,但我不明白你的意思。你能澄清一下吗?
  • 致电self.view.setNeedsLayout() 或/和self.view.layoutIfNeeded()

标签: ios iphone swift swift3


【解决方案1】:

您需要在按钮的两侧设置灵活空间。它会在两边的空间中间保留一个按钮。

试试这个:

let item1 = UIBarButtonItem(customView: sendButton)
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
bottomToolbar.items = [flexibleSpace , item1, flexibleSpace]

【讨论】:

  • 感谢您的回答。但是即使我在右边设置了一个灵活或固定的空间,仍然是同样的问题。
猜你喜欢
  • 1970-01-01
  • 2014-06-12
  • 2017-10-14
  • 2015-06-01
  • 2018-08-21
  • 1970-01-01
  • 2017-06-15
  • 2017-02-27
  • 1970-01-01
相关资源
最近更新 更多