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

标签 ios swift autolayout uikit

我添加了以下代码来使以编程方式添加的 View 居中:

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

这是行不通的。 View 不居中。它仍然在左边。

编辑:

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

最佳答案

friend ,你需要选择一方,如果你使用自动布局,不要用frame初始化你的对象。尝试这样的事情......

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)

}

如果您的 LineChartView 对象是 UIView 的子类,那么这应该有效,并且您的 super View 中间应该有一个 50x50 的对象。

如果您要在代码中进行这样的约束,您应该考虑使用 Apples Visual Formatting Language .

关于ios - 在 Swift 中以编程方式添加约束不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34331622/

相关文章:

ios - 为 card.io 创建 appcelerator 模块时出现正常 x86_64 错误

arrays - 在 UITableview swift 中使用两个数组

ios - View 变换旋转使 iOS 中的图像渲染效果无效

ios - setNeedsLayout 与 setNeedsUpdateConstraints 和 layoutIfNeeded 与 updateConstraintsIfNeeded

ios - 横向/纵向的布局更改

ios - 调度组串行队列

ios - UISearchDisplayController 更改变暗的 View 框架

ios - 读取自定义对象的数据以填充 TableView

ios - 如何在 Storyboard 中使用大小类和自动布局?

iphone - 使用 MPMoviePlayerController 播放 iTunes 预览视频