gpt4 book ai didi

ios - 具有动态约束的 IBDesignable View : Misplaced Children when Rendering

转载 作者:行者123 更新时间:2023-11-28 12:18:59 26 4
gpt4 key购买 nike

我正在尝试构建(以编程方式)一个新 View 并使用 IBDesignable 属性来简化此过程并在 Storyboard 中显示 View 而不是白色矩形。

这是一个有两个 subview 的类:UILabelUIImageView。我将它们动态添加到父 View 并为它们设置了几个约束:

import UIKit

@IBDesignable
class ChoiceView: UIView {

enum ChoiceState {
case empty, chosen
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViewForState(.empty)
}

override init(frame: CGRect) {
super.init(frame: frame)
setupViewForState(.empty)
}

override func awakeFromNib() {
super.awakeFromNib()
}

override func layoutSubviews() {
super.layoutSubviews()
}

private func setupViewForState(_ state: ChoiceState) {
guard case .empty = state else { return } // single case for now

let placeholder = UILabel()
let choiceImage = UIImageView(image: UIImage(named: "plus_small"))
placeholder.text = "None"
placeholder.textAlignment = .right
choiceImage.contentMode = .center

let constraintFormats = [
"H:|-0-[placeholder]-10-[choice(50)]-0-|",
"V:|-0-[placeholder]-0-|",
"V:|-0-[choice]-0-|"
]

let views = ["placeholder": placeholder, "choice": choiceImage]

translatesAutoresizingMaskIntoConstraints = false
placeholder.translatesAutoresizingMaskIntoConstraints = false
choiceImage.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholder)
addSubview(choiceImage)

let constraints = constraintFormats.flatMap {
NSLayoutConstraint.constraints(
withVisualFormat: $0,
options: .directionLeadingToTrailing,
metrics: nil,
views: views)
}

NSLayoutConstraint.activate(constraints)
}

}

这些还不完美,但至少 - 在模拟器中显示: cell in simulator

但是当我在 Storyboard Builder 中重新加载 View 时,我看到了这个: cell in storyboard

如您所见, Storyboard 中未强制执行约束,图像也未显示。你知道怎么解决吗?或者,是否有可能在 Storyboard和模拟器中获得相同的图片?


Solution: Please look at @DonMag answer. It allows to see result I was expecting (see picture attached).

enter image description here

最佳答案

不要为您的可设计 View 本身设置translatesAutoresizingMaskIntoConstraints = false

    let views = ["placeholder": placeholder, "choice": choiceImage]

// don't do this one
//translatesAutoresizingMaskIntoConstraints = false
placeholder.translatesAutoresizingMaskIntoConstraints = false
choiceImage.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholder)
addSubview(choiceImage)

此外,要在 IB 中查看您的“选择”图像:

    let theBundle = Bundle(for: type(of: self))
let choiceImage = UIImageView(image: UIImage(named: "plus_small", in: theBundle, compatibleWith: self.traitCollection))
//
//let choiceImage = UIImageView(image: UIImage(named: "plus_small"))
...

关于ios - 具有动态约束的 IBDesignable View : Misplaced Children when Rendering,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45466466/

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