你好。
使用Swift4,我试图将带有XIB的自定义uiView加载到uiviewController上。
然而,它似乎只占了屏幕的一部分,我不知道为什么。
我做了以下工作:
-
视图控制器在uiStoryboard中定义
-
将uiview添加到
viewDidLoad
-
uiview swift文件和xib通过文件所有者属性连接。
-
XIB文件被添加到
copy bundle resources
-
热粉色背景色是使用Xcode可视化编辑器设置的,它不是在代码中完成的。
-
我使用iphone xr进行模拟,但如果在iphone 6s上进行模拟,我也会遇到同样的问题。
视图控制器代码为空,但我已包含相关部分:
// QuestionViewController
class QuestionViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let subview = QuestionView()
self.view.addSubview(subview)
}
}
uiview也是非常基本的:
class QuestionView: UIView, XibView {
override init(frame: CGRect) {
super.init(frame: frame)
setupXib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupXib()
}
func setupXib() {
guard let v = loadFromXib() else {
return
}
addSubview(v)
}
}
我使用在stackoverflow上找到的协议从bundle加载XIB文件。最初我甚至在加载包时也遇到了很多问题,但很明显我能够纠正这个问题。无论如何,我的XIB协议文件在这里:
// XIB protocol file
protocol XibView {
func setupXib()
func constrainView(_ view: UIView)
func loadFromXib() -> UIView?
}
extension XibView where Self: UIView {
func setupXib() {
if let xibView = loadFromXib() {
addSubview(xibView)
constrainView(xibView)
}
}
func constrainView(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|[view]|",
options: [.alignAllCenterX, .alignAllCenterY],
metrics: nil,
views: ["view": view]
)
)
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "H:|[view]|",
options: [.alignAllCenterX, .alignAllCenterY],
metrics: nil,
views: ["view": view]
)
)
}
func loadFromXib() -> UIView? {
let xibView = UINib(nibName: String(describing: Self.self), bundle: Bundle(for: type(of: self))).instantiate(withOwner: self, options: nil).first as? UIView
return xibView
}
}
——
问题:
为什么uiview不填充整个屏幕,或者只部分填充屏幕,我如何解决这个问题?
以谢
编辑:
故事板查找的uiviewcontroller只有一个没有内容的视图。