gpt4 book ai didi

swift - 从 Bundle 加载 UIView 只会部分填满屏幕

转载 作者:行者123 更新时间:2023-11-28 05:47:05 25 4
gpt4 key购买 nike

Screenshot from simulator iphone xr

你好。

使用 Swift 4,我试图将带有 XIB 的自定义 UIView 加载到 UIViewController 上。

但是,它似乎只是部分填满了屏幕,我不确定为什么。

我做了以下事情:

  1. View Controller 在 UIStoryboard 中定义
  2. viewDidLoad
  3. 中添加 UIView 的 UIViewController
  4. UIView swift 文件和 XIB 通过 File Owner 属性连接
  5. XIB 文件被添加到copy bundle resources
  6. 亮粉色背景颜色是使用 Xcode 可视化编辑器设置的,不是用代码完成的。
  7. 我是用iphone xr模拟的,在iphone 6s上模拟也是一样的问题

View Controller 代码是空的,但我包含了相关部分:

// 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 上找到的协议(protocol)从包中加载 xib 文件。最初我在加载 bundle 时遇到了很多问题,但幸运的是我能够纠正这个问题。不管怎样,我的 XIB 协议(protocol)文件在这里:

// 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 没有填满整个屏幕或只填满屏幕的一部分,我该如何解决这个问题?

谢谢

编辑:

Storyboard查找 UIViewController 只有一个没有内容的 View 。

Storyboard

最佳答案

我觉得你应该在你的Viewcontroller中拿一个UIview(0,0,0,0 四个约束)然后给它分配一个自定义类,它是UIView的一个子类,然后加载Xib文件,它肯定会占据整个屏幕

试试这个人::----

 class QuestionViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let subview = QuestionView()
subview.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.width)
self.view.addSubview(subview)
}
}

关于swift - 从 Bundle 加载 UIView 只会部分填满屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54262941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com