gpt4 book ai didi

ios - 当我禁用/启用按钮时, View 如何重绘自身?

转载 作者:行者123 更新时间:2023-12-01 19:44:35 25 4
gpt4 key购买 nike

如果我启用/禁用按钮…… View 会调用什么方法?

我已经在 layoutSubviews 上放置了一个断点并且看不到它到达那里。也不会到达 viewController 的 viewWillLayoutSubviews。 .所以我只是想知道它是如何工作的以及它触发了什么方法

最佳答案

这是个好问题。我自己对此很好奇,所以我创建了一个简单的 UIButton子类化并在一些重写的​​方法上放置断点。以下是我的发现:

  • 调用 setEnabled:UIButton我称之为 MyButton 的子类实例在 viewDidLoad
  • 这触发了对 setNeedsDisplay 的调用。方法。它被 setEnabled 内部调用。 UIButton 的方法类(class)。正如您在此屏幕截图中的堆栈跟踪中看到的那样:

    enter image description here
  • 之后 setNeedsDisplay , setNeedsLayout方法被触发。堆栈跟踪类似于之前的调用:

    enter image description here
  • 在此之后,按此顺序调用以下方法:layoutSubviews , drawLayer:inContext: , drawRect:

  • 根据 Apple's documentationUIView类(class),

    When the actual content of your view changes, it is your responsibility to notify the system that your view needs to be redrawn. You do this by calling your view’s setNeedsDisplay() or setNeedsDisplay(_:) method of the view. These methods let the system know that it should update the view during the next drawing cycle. Because it waits until the next drawing cycle to update the view, you can call these methods on multiple views to update them at the same time.



    这里是 enabled 上的文档 UIControl 的 bool 值:

    A Boolean value indicating whether the control is enabled. Set the value of this property to YES to enable the control or NO to disable it. An enabled control is capable of responding to user interactions, whereas a disabled control ignores touch events and may draw itself differently. Setting this property to NO adds the UIControlStateDisabled flag to the control’s state bitmask; enabling the control again removes that flag.



    他们提到禁用的控件可能会以不同的方式重新绘制自己。他们还提到了控件的 state位掩码已更新。所以,我相信,苹果内部的 UIButton类调用 setNeedsDisplay方法,这反过来又迫使重新绘制自己。基于 (UIControlState) state属性,按钮分别绘制自己。您可以在 UIButton 绘图 here (look at Table 2 Appearance attributes) 上找到更多信息和 UIView 绘图 here .

    但它可能不会触发 UIViewController 上的任何事件的 View ,其中按钮作为 subview 。虽然,您可以使用 KVO 并观察 enabled如果您想在 View Controller 或按钮的 super View 中监听属性的更改,请使用属性。

    关于ios - 当我禁用/启用按钮时, View 如何重绘自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49984673/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com