import UIKit
class ViewController: UIViewController {
@IBOutlet weak var vsuper: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let v = view2.getView()
vsuper.backgroundColor = UIColor.black
vsuper.addSubview(v)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//xib file
import UIKit
class view2: UIView {
override func awakeFromNib() {
super.awakeFromNib()
}
static func getView()->view2{
let v = Bundle.main.loadNibNamed("view2", owner: nil, options: nil)?.first as! consentview
// v.translatesAutoresizingMaskIntoConstraints = false
return v;
}
}
While I load xib into another view in story board it doesn't get added inside that view if translateautoresizingmaskintoconstraints is set to false but if I remove that line it gets added to the view.
if I set it to false it takes space on top left otherwise it gets added inside the view. Why so ? even though I am adding it tov super
Try it
import UIKit
class MyView: UIView {
// your outlets from your view can be there
// your functions for your view
func myFunc() {
}
}
import UIKit
class ViewController: UIViewController {
var myView: MyView!
override func viewDidLoad() {
super.viewDidLoad()
if let contentView = Bundle.main.loadNibNamed("MyView", owner: self, options: nil)?.first as? MyView {
myView = contentView
self.view.addSubview(myView)
}
// set background color your custom view
myView.backgroundColor = UIColor.black
// call functions for your custom view
myView.myFunc()
}
}
You did not set the constraints. translatesAutoresizingMaskIntoConstraints = false
means you don't want the xib frame to be translated into constraints thus you will setup constraints yourself. Thats why its not assigning any bounds to the xib view on your superview. Try making some constraints with the superview after addSubview() call. such as,
v.leadingAnchor.constraint(equalTo: vsuper.leadingAnchor, constant: 0).isActive = true
v.trailingAnchor.constraint(equalTo: vsuper.trailingAnchor, constant: 0).isActive = true
v.topAnchor.constraint(equalTo: vsuper.topAnchor, constant: 0).isActive = true
v.bottomAnchor.constraint(equalTo: vsuper.bottomAnchor, constant: 0).isActive = true
vsuper.layoutIfNeeded()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.