gpt4 book ai didi

ios - Swift 从 Nib 创建自定义 View

转载 作者:行者123 更新时间:2023-11-28 09:49:53 27 4
gpt4 key购买 nike

我尝试使用 Nib 文件实现自定义加载器 View 。但我得到一个错误在 loadViewFromNib()

return nib.instantiate(withOwner: self, options: nil).first as? UIView.

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee6f3df98)

open class LoaderView: UIView {

@IBOutlet var loaderImage: UIImageView!
@IBOutlet var contentView: UIView!

func xibSetup() {
contentView = loadViewFromNib()
contentView.frame = bounds
contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(contentView)
}

required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}

override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}

func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "LoaderView", bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}

我在 VC 中的 viewDidLoad() 中将这个加载器称为

let loader = LoaderView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
view.addSubview(loader)

最佳答案

你的代码很好,没有递归

请确保你有

1) 仔细检查您的 IBOUtlet 连接

2) 在File's Owner 中添加了你的类


enter image description here

enter image description here

我已经创建了这个和你的代码一样

class CustomView: UIView {

let nibName = "CustomView"
@IBOutlet var view : UIView!

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetUp()
}

override init(frame: CGRect) {
super.init(frame: frame)
xibSetUp()
}

func xibSetUp() {
view = loadViewFromNib()
view.frame = self.bounds
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(view)
}

func loadViewFromNib() -> UIView {

let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CustomView", bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as! UIView

}

}

查看输出

enter image description here

关于ios - Swift 从 Nib 创建自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51186987/

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