当 UIButton 的子视图是 UITableViewCell 的子视图或任何其他视图的子视图时,设置 UIButton 边缘插入的理想位置是什么

What is the ideal place to set edge insets of UIButton when its subview of a UITableViewCell or subview of Any other View

我有一个场景,我需要为添加到 UITableViewCell 的 UIButton 更改 UIEdgeInsets,我在 layoutSubviews 中设置了它,但它被调用了很多次,它也适用于 init,但我不确定这是否真的一个地方,因为它只会调用一次。

override func layoutSubviews() {
        super.layoutSubviews()
        if imageView != nil {
            titleEdgeInsets = UIEdgeInsets(top: 52, left: -10, bottom: 0, right:-10)
        }
    }

谁能告诉我哪一个是 理想的地方,为什么?

如果您使用 xib,请使用 awakeFromNib()

它调用了一次,这从文档到 awakeFromNib():

Typically, you implement awakeFromNib for objects that require additional set up that cannot be done at design time. For example, you might use this method to customize the default configuration of any controls to match user preferences or the values in other controls. You might also use it to restore individual controls to some previous state of your application.

或者,如果您不使用 xib,只需使用 init,因为它调用了一次。

awakeFromNib 将在从 xib 或故事板加载新单元格时调用 ,但不是在重新使用单元格时。 但是在 awakeFromNib 期间,框架布局不会出现。 UIEdgeInsets 不会受框架影响,所以我更喜欢在 awakeFromNib 中调用它,而不是在 布局子视图

layoutSubviews 您将获得正确的框架,因此仅用于需要正确框架(如角半径)的时尚产品