gpt4 book ai didi

ios - 以编程方式添加约束时找不到 super View ?

转载 作者:搜寻专家 更新时间:2023-11-01 06:17:07 26 4
gpt4 key购买 nike

提到这个问题Making a custom UIView subview that fills its superview在尝试以编程方式添加约束时。

我正在使用下面的代码以编程方式添加两个约束;但是,我收到一条错误消息,指出“无法解析约束格式”,因为相关 View 没有父 View 。

private func setupDownView(view: UIView) {
let downView = try? DownView(frame: view.bounds, markdownString: "")
downView!.translatesAutoresizingMaskIntoConstraints = false
let viewsDict = ["view": downView!]
downView!.addConstraint(NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[view]-0-|",
options: [],
metrics: nil,
views: viewsDict)[0])
downView!.addConstraint(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[view]-0-|",
options: [],
metrics: nil,
views: viewsDict)[0])
view.addSubview(downView!);
}

enter image description here

view 是否在添加到其 subview 后自动成为父 View ?

我尝试在 addConstraint 之前通过 addSubview 设置约束之前添加 View ,但我收到错误“ View 层次结构未为约束准备”。

enter image description here

setupDownView在下面两个地方被调用,

@IBOutlet weak var cardTags: UIView! {didSet { setupDownView(view: cardTags)}}
@IBOutlet weak var cardContent: UIView! {
didSet {
setupDownView(view: cardContent)
let tap = UILongPressGestureRecognizer(
target: self,
action: #selector(QuizViewController.tapDownHandler)
)
tap.minimumPressDuration = 0
cardContent.addGestureRecognizer(tap)
}
}

最佳答案

在层次结构中之后需要添加约束。所以 addSubview 调用必须在之前 addConstraint 调用。

还要确保 addConstraint 是在其父 View 上调用的,而不是 downView,并且 constraintsWithVisualFormat 返回的所有 约束:被添加,不仅仅是第一个。

private func setupDownView(view: UIView) {
let downView = try? DownView(frame: view.bounds, markdownString: "")
downView!.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(downView!);

let viewsDict = ["view": downView!]
view.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[view]-0-|",
options: [],
metrics: nil,
views: viewsDict))
view.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[view]-0-|",
options: [],
metrics: nil,
views: viewsDict))

view.layoutIfNeeded()
}

关于ios - 以编程方式添加约束时找不到 super View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42186834/

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