簡體   English   中英

Swift4問題:以編程方式更改Nslayoutconstraint

[英]Swift4 issues : change Nslayoutconstraint programmatically

我想以編程方式將UITextfield txtAmount NSLayoutConstraint的位置從其集合視圖的頂部到底部更改為圖像視圖的底部。 所有視圖都嵌入到ui視圖中。

從情節提要中拖動並映射舊約束到視圖控制器。 新的約束構造將以編程方式創建。

說到實現和執行,它說

When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled.
'Unable to install constraint on view.  Does the constraint reference something from outside the subtree of the view?  That's illegal. 

您能告訴我有關此類修改的任何准則嗎? 由於使用了scrollview,我將UI元素嵌入了嵌入式UIView中。

    let constr = NSLayoutConstraint(item: txtAmount, attribute: .top, relatedBy: .equal, toItem: imageView, attribute: .bottom , multiplier: 1, constant: 0)

    IETypeList.removeFromSuperview()
    uiviewType.removeFromSuperview()

    txtAmount.addConstraint(constr)
    txtAmount.removeConstraint(constraintPo)

在此處輸入圖片說明

要添加約束到txtAmount而你應該已經把它添加到實際包含視圖txtAmount並在此約束引用另一種觀點,即imageView 讓我們將包含它們的superview命名為superview

let constr = NSLayoutConstraint(item: txtAmount, attribute: .top, relatedBy: .equal, toItem: imageView, attribute: .bottom , multiplier: 1, constant: 0)

IETypeList.removeFromSuperview()
uiviewType.removeFromSuperview()

txtAmount.removeConstraint(constraintPo)
superview.addConstraint(constr)

但這是自iOS 8以來不推薦的方法。正如文檔所述 ,您應該將約束isActiveread this )屬性設置為true ,iOS會將它們添加到相關視圖中:

IETypeList.removeFromSuperview()
uiviewType.removeFromSuperview()

constraintPo.isActive = false
constr.isActive = true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM