gpt4 book ai didi

ios - 自定义 UIControl 中的帧大小和 'required init(coder: NSCoder)'

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:16 25 4
gpt4 key购买 nike

我有一个自定义 UIControl,我实现为:

required init(coder: NSCoder) {
super.init(coder: coder)
initSubComponents()
}

func initSubComponents() {
// Display UIControl border for visual debugging
self.layer.borderColor = UIColor.redColor().CGColor
self.layer.borderWidth = 3.0

subviewContainer = UIView(frame: self.bounds.rectByInsetting(dx: 0, dy: 0))
// Display container border for visual debugging
subviewContainer.layer.borderColor = UIColor.redColor().CGColor
subviewContainer.layer.borderWidth = 3.0

println("UIControl frame: \(self.frame)")
println("subviewContainer frame: \(subviewContainer.frame)")
}

override func drawRect(rect: CGRect) {
initSubComponents()
// Code to add those subviews into this UIControl
}

func initSubComponents() {
// Display UIControl border for visual debugging
self.layer.borderColor = UIColor.redColor().CGColor
self.layer.borderWidth = 3.0

subviewContainer = UIView(frame: self.bounds.rectByInsetting(dx: 0, dy: 0))
// Display container border for visual debugging
subviewContainer.layer.borderColor = UIColor.redColor().CGColor
subviewContainer.layer.borderWidth = 3.0

println("UIControl frame: \(self.frame)")
println("subviewContainer frame: \(subviewContainer.frame)")
}

我发现一个我不明白的情况:我从上面2种不同的方法得到的frame是不一样的!为什么?第一种方法应该更好,因为我不应该在 override func drawRect(rect: CGRect) 中初始化,但是我在第二种方法中得到了我期望的确切帧,而不是第一种方法!

最佳答案

发生这种情况是因为在初始化时控件正在从 Storyboard / Nib 获取它的框架。在首次布局之前, Storyboard / Nib 中的 View 大小可能与设备上的大小不同。

正如评论中的人所说,drawRect 不断被调用,因此它具有正确的框架,因为控件已经布置好。但这是初始化子组件的错​​误位置。同样作为默认实现状态,除非您实际上在 drawRect 中绘制某些东西,否则您不应该使用它,因为它会对性能产生不利影响。

我现在可以想到几个解决问题的方法:

  1. 使用约束在 initWithCoder 方法中初始化子组件,并在布局控件时依靠自动布局更新所有内容。
  2. 使用标志仅初始化一次子组件。等待 layoutSubviews 中的第一个布局并从那里初始化。

关于ios - 自定义 UIControl 中的帧大小和 'required init(coder: NSCoder)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29691733/

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