Swift Playgrounds计划中的程序化约束问题

时间:2017-04-02 05:49:37

标签: ios swift constraints

想知道如何更新自定义UI视图的约束。绝对是我的代码中的错误。我提前道歉,我只是Swift的初学者。

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

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些问题:

  1. Rob在评论中提到: 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
    

    这意味着,您尝试将true分配给NSLayoutXAxisAnchor类型的变量。同样适用于bottomAnchor

    2B。至于leftAnchor的类型 - 它应该是NSLayoutConstraint,因为在锚点上调用constraint会创建NSLayoutConstraint。如果您想获取对锚点的引用,只需拨打leftAnchor = contentView.leftAnchor

  3. 您不仅要设置约束,还要设置覆盖updateConstraints方法的整个视图。虽然这没有错,但我会用这么简单的观点来反对它。我宁愿制作一个public func setup()方法,并从视图控制器viewDidLoad调用它来设置视图及其约束。

  4. 对于手势识别器 - 您还需要将其添加到视图中,仅初始化它是不够的。简单的self.addGestureRecognizer(self.titleLabelGestureRecognizer)应该可以解决问题。