Reputation: 17132
I'm creating a view to use it as a subview within the viewDidLoad.
override func viewDidLoad() {
let backgroundView = UIView()
backgroundView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.backgroundColor = UIColor.blackColor()
let viewsDictionary = ["backgroundView":backgroundView]
let backgroundView_constraint_H = NSLayoutConstraint.constraintsWithVisualFormat(
"H:[backgroundView(10000)]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil, views: viewsDictionary)
let backgroundView_constraint_V = NSLayoutConstraint.constraintsWithVisualFormat(
"V:[backgroundView(10000)]",
options: NSLayoutFormatOptions(rawValue:0),
metrics: nil, views: viewsDictionary)
backgroundView.addConstraints(backgroundView_constraint_H)
backgroundView.addConstraints(backgroundView_constraint_V)
backgroundView.alpha = 0.9
self.tableView.backgroundView = backgroundView
}
What's the correct workaround to put all the code into an own .swift file and only call self.tableView.backgroundView = backgroundView
at the viewDidLoad?
Help is very appreciated.
Upvotes: 0
Views: 148
Reputation: 711
class func backgroundView()->UIView {
let backgroundView = UIView()
backgroundView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.backgroundColor = UIColor.blackColor()
backgroundView.frame = self.tableView.frame
backgroundView.alpha = 0.9
self.tableView.backgroundView = backgroundView
Upvotes: 2
Reputation: 6514
You can extend UIView itself and write a class function that would return you this background view correctly configured. Save this in a file say UIView+extensions.swift
extension UIView {
class func backgroundView()->UIView {
let backgroundView = UIView()
backgroundView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.backgroundColor = UIColor.blackColor()
let viewsDictionary = ["backgroundView":backgroundView]
let backgroundView_constraint_H = NSLayoutConstraint.constraintsWithVisualFormat(
"H:[backgroundView(10000)]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil, views: viewsDictionary)
let backgroundView_constraint_V = NSLayoutConstraint.constraintsWithVisualFormat(
"V:[backgroundView(10000)]",
options: NSLayoutFormatOptions(rawValue:0),
metrics: nil, views: viewsDictionary)
backgroundView.addConstraints(backgroundView_constraint_H)
backgroundView.addConstraints(backgroundView_constraint_V)
backgroundView.alpha = 0.9
return backgroundView
}
}
You can now access this as:
self.tableView.backgroundView = UIView.backgroundView()
Upvotes: 1