String is not identical to NSObject error, applying constraints in Swift (visual constraints)
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)
}
}
source to share
The parameter views
constraintsWithVisualFormat
expects a dictionary of type [NSObject: AnyObject]
.
When creating, viewsDict
try to declare it like [NSObject: AnyObject]
:
var viewsDict: [NSObject: AnyObject] = ["imageView": fullImage!, "nameLabel": nameLabel!, "detailLabel": detailLabel!]
You will also have to change the value of the options
param parameter from 0
tonil
Also, if you want to get rid of the options, you can try this:
var fullImage = UIImageView()
var nameLabel = UILabel()
var detailLabel = UILabel()
Instead:
var fullImage: UIImageView?
var nameLabel: UILabel?
var detailLabel: UILabel?
Then, for the declaration, viewsDict
you can remove !
:
var viewsDict: [NSObject: AnyObject] = ["imageView": fullImage, "nameLabel": nameLabel, "detailLabel": detailLabel]
source to share