Ios 无限循环尝试使用Xcode 11 beta从swift 5中的xib创建自定义视图
我想使用Xcode 11 beta在swift 5中创建一个可重用的UI框架。我的框架类是:Ios 无限循环尝试使用Xcode 11 beta从swift 5中的xib创建自定义视图,ios,xcode11,swift5,Ios,Xcode11,Swift5,我想使用Xcode 11 beta在swift 5中创建一个可重用的UI框架。我的框架类是: import UIKit @IBDesignable open class MyFramework: UIView { var view: UIView! @IBOutlet weak var helloLabel: UILabel! var nibName: String = "MyFramework" public override init(frame: C
import UIKit
@IBDesignable
open class MyFramework: UIView {
var view: UIView!
@IBOutlet weak var helloLabel: UILabel!
var nibName: String = "MyFramework"
public override init(frame: CGRect) {
// For use in code
super.init(frame: frame)
setUpView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func awakeFromNib() {
super.awakeFromNib()
setUpView()
}
private func setUpView() {
if let contentView = Bundle.main.loadNibNamed(self.nibName, owner: self, options: nil)?.first as? UIView {
contentView.frame = self.bounds
self.addSubview(contentView)
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
helloLabel.text = ""
}
}
public func set(helloLabel text: String) {
self.helloLabel.text = text
}
override open func layoutSubviews() {
super.layoutSubviews()
}
}
在我的xib文件中,我刚刚添加了一个标签
当我在另一个项目中使用此框架时,由于名为无限时间的setUpView()而导致EXC_BAD_访问错误
import MyFramework
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let view = MyFramework()
view.set(helloLabel: "Hello World!!!!")
}
}
请帮忙 在
setUpView
方法中调用Bundle.main.loadNibNamed
时,视图从nib加载,因此调用awakeFromNib
,后者反过来调用setUpView
,并导致无限循环
我不知道为什么只需要从nib加载内容视图,然后将其添加为子视图,而不是从nib加载整个自定义视图。但如果您坚持这样做,至少在从nib加载内容视图后,将实例变量maybecontentView:view?
设置为加载的内容视图。并在设置视图中添加一个复选框,如果内容视图不是nil,只需返回即可
而您在setUpView
中加载的nib,因为它仅用于内容视图,绝对不应该是self。nib
只需将setUpView移动到init(编码器:NSCoder)方法