2017-04-02 53 views
0

想知道如何更新自定義UI視圖的約束。在我的代碼中肯定是錯誤的。我提前道歉,我只是Swift的初學者。Swift Playgrounds中的Programmatic Constraint問題程序

public class NoteCardView:UIView { 
@IBInspectable var contentView = UIButton(frame: .zero) 
@IBInspectable var delegate: MainViewController? 
var leftAnchor: NSLayoutXAxisAnchor 
var bottomAnchor: NSLayoutYAxisAnchor 

override public func updateConstraints() { 

    contentView.translatesAutoresizingMaskIntoConstraints = false 

    contentView.layer.masksToBounds = true 
    contentView.layer.cornerRadius = 6 
    contentView.widthAnchor.constraint(equalToConstant: 75).isActive = true 
    contentView.heightAnchor.constraint(equalToConstant: 100).isActive = true 
    leftAnchor = contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: positionX).isActive = true 
    bottomAnchor = contentView.bottomAnchor.constraint(equalTo: (delegate?.view.bottomAnchor)!, constant: positionY).isActive = true 
    titleLabel.textAlignment = .center 
    titleLabel.text = note 
    contentView.addSubview(titleLabel) 


    super.updateConstraints() 
} 

class MainViewController: UIViewController { 
override func viewDidLoad() { 
// Trying to implement updated constraints to the NoteCardView here. 
} 
} 

還有這個與TapGestureRecognizer無關的其他問題。我對這個概念也不是很熟悉。

public class NoteCard:UIView { 
internal var titleLabelTapGestureRecognizer: UITapGestureRecognizer? 

internal func commonInit() { 
self.titleLabelTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTitleLabelTap(UITapGestureRecognizer))) 
} 

internal func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) { 
    self.delegate?.noteCardViewTitleLabelDidRecieveTap(self) 
} 
} 

預先感謝您的幫助!

+2

如果沒有別的,您的左側錨點位於內容視圖和其本身之間,這是沒有意義的。此外,您通常需要在設置任何約束之前將視圖添加到層​​次結構中。如果您收到基於約束的錯誤消息,請分享精確的消息(修復上述約束後)。 – Rob

回答

0

有幾個問題在你的代碼:

  1. 什麼搶在他的評論中提到: contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: positionX) - 這是沒有意義的,因爲制約 應該是兩種不同的角度錨之間。在向層次結構添加視圖之後,還應配置約束。
  2. 與同一行

    另外:leftAnchor = contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: positionX).isActive = true。此行有實際上是兩個問題 :

    2A。這種化合物賦值語句這樣:

    contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: positionX).isActive = true 
    leftAnchor = true 
    

    這意味着,你嘗試分配trueNSLayoutXAxisAnchor類型的變量。同樣適用於bottomAnchor

    2B。至於leftAnchor類型 - 它應該是NSLayoutConstraint,因爲錨調用constraint創建NSLayoutConstraint。如果您想要獲取錨點的參考,則只需撥打leftAnchor = contentView.leftAnchor即可。

  3. 您不僅設置了您的約束條件,還設置了覆蓋updateConstraints方法的整個視圖。雖然這沒有錯,但我會用這麼簡單的意見來反對它。我寧願製作一個public func setup()方法,並從視圖控制器viewDidLoad中調用它來設置視圖及其約束。

  4. 至於手勢識別器 - 您還需要將它添加到視圖,它是不夠初始化它。簡單self.addGestureRecognizer(self.titleLabelGestureRecognizer)應該做的伎倆。

相關問題