简体   繁体   English

在Swift中以编程方式添加约束不起作用

[英]Programmatically adding constraints in Swift does not work

I added the following code to center a programmatically added view: 我添加了以下代码以使以编程方式添加的视图居中:

let horizontalConstraint = NSLayoutConstraint(item: newView!, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
view.addConstraint(horizontalConstraint)

It doesn't work. 没用 The view is not centered. 视图未居中。 It is on the left still. 它在左边。

EDIT: 编辑:

    override func viewDidLoad() {
    super.viewDidLoad()

    newView = LineChartView(frame: CGRectMake(0, 0, 50, 50))
    newView?.delegate = self
    newView?.drawBordersEnabled = true
    newView?.noDataText = "No Data"
    newView?.noDataTextDescription = "No Data"
    newView?.borderColor = UIColor.blackColor()

    self.view.addSubview(newView!)

You need to pick a side my friend, If you are using auto layout, don't initialise your objects with a frame . 我的朋友需要挑一面,如果您使用的是自动布局,请不要使用frame初始化对象。 Try something like this... 试试这样的东西...

var newView:LineChartView!

override func viewDidLoad() {
    super.viewDidLoad()

    newView = LineChartView()
    newView.translatesAutoresizingMaskIntoConstraints = false
    newView.delegate = self
    newView.drawBordersEnabled = true
    newView.noDataText = "No Data"
    newView.noDataTextDescription = "No Data"
    newView.borderColor = UIColor.blackColor()
    self.view.addSubview(newView)

    let width = NSLayoutConstraint(item: newView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 50)
    let height = NSLayoutConstraint(item: newView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 50)
    newView.addConstraint(width)
    newView.addConstraint(height)
    let x = NSLayoutConstraint(item: newView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0)
    let y = NSLayoutConstraint(item: newView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)
    self.view.addConstraint(x)
    self.view.addConstraint(y)

}

If your LineChartView object is a subclass of UIView then this should work, and you should have a 50x50 object in the middle of your superview. 如果LineChartView对象是UIView的子类,则这应该可以工作,并且您的超级视图中间应该有50x50的对象。

If you are going to be doing constraints like this in code you should consider using Apples Visual Formatting Language . 如果要在代码中进行此类约束,则应考虑使用Apples Visual Formatting Language

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM