我想以编程方式向视图添加自定义按钮,并设置该按钮的约束。这是我的代码:
let button = SummaryButton(frame: CGRect(x: 0, y: 0, width: 36, height: 36))
button.setTitle("1", for: .normal)
button.addTarget(self, action: #selector(daysButtonPressed), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
daysView.addSubview(button)
NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: daysView, attribute: .leading, multiplier: 1.0, constant: 20).isActive = true
NSLayoutConstraint(item: button, attribute: .centerX, relatedBy: .equal, toItem: daysView, attribute: .centerX, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 36).isActive = true
NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: 36).isActive = true
我根本看不到按钮。如果我删除约束,我可以看到它,但位置不正确。
我是如何设置约束的?我想添加到视图的左侧。
答案 0 :(得分:1)
删除centerX约束,因为您已有前导
NSLayoutConstraint(item: button, attribute: .centerX, relatedBy: .equal, toItem: daysView, attribute: .centerX, multiplier: 1.0, constant: 0).isActive = true
并从视图顶部添加前50个点
NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: daysView, attribute: .top, multiplier: 1.0, constant: 50).isActive = true