字符串与NSObject错误不同,同时在Swift中应用约束(视觉约束)

时间:2014-12-30 14:28:49

标签: ios swift nsdictionary nslayoutconstraint

import UIKit
import Foundation
class DetailView: UIViewController{
    var fullImage:UIImageView?
    var nameLabel:UILabel?
    var detailLabel:UILabel?

    override  func viewDidLoad() {
        super.viewDidLoad()
        fullImage = UIImageView()
        nameLabel = UILabel()
        detailLabel = UILabel()
        self.view.addSubview(fullImage!)
        self.view.addSubview(nameLabel!)
        self.view.addSubview(detailLabel!)
    }

    func applyContraints(){
        self.view.addSubview(fullImage!)

     fullImage?.setTranslatesAutoresizingMaskIntoConstraints(false)
     nameLabel?.setTranslatesAutoresizingMaskIntoConstraints(false)
     detailLabel?.setTranslatesAutoresizingMaskIntoConstraints(false)

        var viewsDict:[String:AnyObject!] = ["imageView": fullImage!, "nameLabel": nameLabel!, "detailLabel": detailLabel!]

        var constraints:NSArray

        constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[imageView]-10-|",
            options: 0,
            metrics: nil,
            views: viewsDict)
        self.view.addConstraints(constraints)



    }
}

2 个答案:

答案 0 :(得分:5)

views的{​​{1}}参数需要类型为constraintsWithVisualFormat的词典。

创建[NSObject: AnyObject]时,请尝试将其声明为viewsDict

[NSObject: AnyObject]

您还必须将var viewsDict: [NSObject: AnyObject] = ["imageView": fullImage!, "nameLabel": nameLabel!, "detailLabel": detailLabel!] 参数值从options更改为0

另外,如果您想摆脱选项,可以尝试以下方法:

nil

而不是:

var fullImage = UIImageView()
var nameLabel = UILabel()
var detailLabel = UILabel()

然后,对于var fullImage: UIImageView? var nameLabel: UILabel? var detailLabel: UILabel? 声明,您可以删除viewsDict

!

答案 1 :(得分:5)

请将options:0更改为options: NSLayoutFormatOptions(0),这是正确的语法。