【发布时间】:2023-03-19 04:10:01
【问题描述】:
我有一个自定义视图,我正尝试从自定义 XIB 加载,但加载时视图显示为空白,即使在调试时认为它具有正确的大小。
我的调试语句显示框架的大小正确:
commonInit()
XIB:MyCustomView
myView 帧:(0.0, 0.0, 320.0,568.0)
myView ContentSize: (320.0, 710.0)
这是我用来调用自定义视图的自定义 VC
class MyCustomViewController: UIViewController {
var myView : MyCustomView!
override func viewDidLoad() {
super.viewDidLoad()
myView = MyCustomView(frame: self.view.frame)
self.view.addSubview(myView)
updateScrollViewSize()
print("myView Frame: \(myView.frame)")
print("myView ContentSize: \(myView.contentView.contentSize)")
}
func updateScrollViewSize () {
var contentRect = CGRect.zero
for view in myView.contentView.subviews {
contentRect = contentRect.union(view.frame)
}
myView.contentView.contentSize = CGSize(width: myView.contentView.frame.size.width, height: contentRect.size.height + 5)
}
}
有一个XIB,其文件所有者为MyCustomView,并且所有出口都正确连接。
class MyCustomView: UIView {
let kCONTENT_XIB_NAME = "MyCustomView"
@IBOutlet var contentView: UIScrollView!
@IBOutlet weak var lbl_datein: UILabel!
//.. A bunch of other GUI elements for the scrollview
@IBOutlet weak var text_location: UITextField!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
print(#function)
print("XIB: \(kCONTENT_XIB_NAME)")
Bundle.main.loadNibNamed(kCONTENT_XIB_NAME, owner: self, options: nil)
contentView.addSubview(self)
contentView.frame = self.bounds
contentView.backgroundColor = .blue
}
}
有没有人看到我在尝试加载视图时做错了什么
【问题讨论】:
-
我试过了,setNeedsLayout 没用。
-
基本上,你想要
self.addSubview(contentView),而不是相反。
标签: ios swift storyboard xib nib