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

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

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!);
}

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

view添加到其子视图后,它会自动成为 super 视图吗?

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

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

在以下两个地方调用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)上调用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()
}

10-08 08:19
查看更多