我创建了两个客户思想xib并添加了约束 如下:
UIView1
import UIKit
类TestSubView:UIView {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
@IBOutlet var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
loadViewFfromNib()
setupSubviews()
}
func setupSubviews() {
view = loadViewFfromNib()
print("self.view.bounds")
print(self.view.bounds)
print("self.view.frame")
print(self.view.frame)
addSubview(view)
}
func loadViewFfromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: String(self.dynamicType), bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadViewFfromNib()
setupSubviews()
}
override func layoutSubviews() {
super.layoutSubviews()
//this is for Rect drawer
self.frame=CGRectMake(0, 0, 0, 0)
print(self.view.bounds)
print(self)
print(self.frame)
print(self.superview?.frame)
}
}
UIView2
import UIKit
class Test2SubView:UIView {
override func awakeFromNib() {
super.awakeFromNib()
}
@IBOutlet var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
loadViewFfromNib()
setupSubviews()
}
func setupSubviews() {
view = loadViewFfromNib()
print(self.view.bounds)
addSubview(view)
}
func loadViewFfromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: String(self.dynamicType), bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadViewFfromNib()
setupSubviews()
}
}
IN main.stroyboard
我添加一个带有约束的UIview来加载我的客户UIView
我将它加载到函数doxiblayoutTest
中 func doxiblayoutTest(){
let value="a"
switch value {
case "a":
let v=TestSubView.init()
v.frame.origin=xibLayoutTest.frame.origin
xibLayoutTest.addSubview(v)
case "b":
let v=Test2SubView.init()
xibLayoutTest.addSubview(v)
default:
let v=TestSubView.init()
xibLayoutTest.addSubview(v)
}
print("xibLayoutTest.bounds")
print(xibLayoutTest.bounds)
print(xibLayoutTest.frame.size)
print(xibLayoutTest.frame.origin)
}
结果
但是当我旋转屏幕时。它显示不正确。有谁可以帮助我!!!!