【问题标题】:when re-render layout of UIView, the draw function is not triggeredUIView重新渲染布局时,不会触发draw函数
【发布时间】:2016-11-10 19:47:56
【问题描述】:

我正在使用 Xcode 8.1

我是 UIView 的子类:

class DrawingView: UIView {
   override func draw(_ rect: CGRect) {
        super.draw(rect)
        print("drawing...")
   }

   override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
      // re-renader the layout when finger moves
      setNeedsLayout()
      super.touchesMoved(touches, with: event)
   }
}

当我运行我的应用程序时,上面的draw(...) 函数在应用程序启动时被调用一次。 (我看到了打印消息)

然后,我手指在屏幕上移动,我预计每次手指移动都应该调用draw(...)(因为我调用了setNeedsLayout()), 但是draw(...) 函数永远不会被调用。为什么?

【问题讨论】:

标签: ios uiview ios10


【解决方案1】:

要触发视图重新绘制,请调用setNeedsDisplay(),而不是setNeedsLayout()

【讨论】:

  • 调用setNeedsLayout() 将导致调用layoutSubviews()layoutSubviews() 的实现应该设置所有子视图的框架。尽管您可以在任何地方设置视图框架,但出于性能和代码可读性的考虑,建议您使用该方法进行设置。当你使用约束时,你不需要实现这个方法,框架是由自动布局系统为你使用约束设置的。
猜你喜欢
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
  • 2017-06-09
  • 2023-01-30
  • 1970-01-01
  • 2020-06-20
相关资源
最近更新 更多