想知道如何更新自定义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)
}
}
提前感谢您的帮助!
答案 0 :(得分:0)
您的代码中存在一些问题:
contentView.leftAnchor.constraint(equalTo: contentView.leftAnchor,
constant: positionX)
- 作为约束,这没有意义
应该在两个不同视图的锚点之间。在向层次结构添加视图后,还应配置约束。也使用相同的行: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
。
您不仅要设置约束,还要设置覆盖updateConstraints
方法的整个视图。虽然这没有错,但我会用这么简单的观点来反对它。我宁愿制作一个public func setup()
方法,并从视图控制器viewDidLoad
调用它来设置视图及其约束。
对于手势识别器 - 您还需要将其添加到视图中,仅初始化它是不够的。简单的self.addGestureRecognizer(self.titleLabelGestureRecognizer)
应该可以解决问题。