在嘗試以編程方式添加約束時引用此問題Making a custom UIView subview that fills its superview。以編程方式添加約束時無法找到超級視圖?
我使用下面的代碼來添加兩個約束programmticly;但是,我收到一個錯誤,指出「無法解析約束格式」,因爲相關視圖沒有超級視圖。
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!);
}
是否view
自動成爲上海華一旦被添加到其子視圖?
我試圖在設置約束之前添加視圖addSubview
在addConstraint
之前,並且出現錯誤「視圖層次結構未針對約束進行準備」。
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)
}
}
你能否在下面提供答案作爲參考,對於那些有類似問題的人? –
我添加了我的評論作爲答案。 – vacawama