【发布时间】:2020-01-22 05:51:23
【问题描述】:
我想使用 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: 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 文件中,我刚刚添加了一个标签。
当我在另一个项目中使用此框架时,我收到 EXC_BAD_ACCESS 错误,因为 setUpView() 调用了无限时间。
import MyFramework
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let view = MyFramework()
view.set(helloLabel: "Hello World!!!!")
}
}
请帮助。
【问题讨论】: