gpt4 book ai didi

ios - @IBInspectable : wrong bounds and frames at runtime when I add subviews

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:47:39 25 4
gpt4 key购买 nike

这是我的@IBInspectable:代码:

@IBDesignable
class PBOView: UIView {
@IBInspectable var borderRightColor: UIColor? {
didSet {
let borderRightView = UIView(frame: CGRectMake(frame.size.width - 10, 0, 10, frame.size.height))
borderRightView.backgroundColor = borderRightColor

addSubview(borderRightView)
}
}
}

这是 Storyboard 中的结果:

UIView 的宽度是 150 enter image description here

在 iPhone 模拟器中:UIView 的宽度是150,但因为是iPhone 应该是80这就是为什么矩形在我的自定义 View 中不可见的原因 enter image description here

当我将 clearColor 设置为我的 View 背景时,结果如下: enter image description here

为什么该 UIView 的边界和框架宽度错误?实际上它们是 Storyboard的宽度,而不是运行时的真实宽度。

最佳答案

我正在挖掘一些,但我还没有找到优雅的属性或方法来解决这个问题。到目前为止唯一的方法是:

@IBDesignable
class PBOView: UIView {

var borderRightView: UIView?

@IBInspectable var borderRightColor: UIColor? {
didSet {
addBorderRightView()
}
}

func addBorderRightView() {

borderRightView = UIView(frame: CGRectMake(frame.size.width - 10, 0, 10, frame.size.height))
borderRightView!.backgroundColor = borderRightColor
addSubview(borderRightView!)
}

override func layoutSubviews() {
super.layoutSubviews()

if let borderRightView = borderRightView {
borderRightView.removeFromSuperview()
}
if let borderRightColor = borderRightColor {
addBorderRightView()
}
}
}

只需用您自己的内容覆盖 layoutSubviews() 方法。由于 layoutSubviews() 几乎在任何地方都被调用,所以它可以正常工作。

结果是:

enter image description here

仍在寻找优雅的解决方案 - 适合我的方法。

关于ios - @IBInspectable : wrong bounds and frames at runtime when I add subviews,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30031753/

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