我创建了一个自定义 UIView 作为 .xib 文件,其中 UIView 有一个按钮。我使用下面的代码加载 UIView。
struct ContentView: View {
var body: some View {
CustomViewRepresentable()
}
}
struct CustomViewRepresentable: UIViewRepresentable {
typealias UIViewType = CustomView
func makeUIView(context: UIViewRepresentableContext<CustomViewRepresentable>) -> CustomView {
let customView = Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)![0] as! CustomView
return customView
}
func updateUIView(_ uiView: CustomView, context: UIViewRepresentableContext<CustomViewRepresentable>) {
}
}
自定义视图具有以下代码:
class CustomView: UIView {
@IBOutlet weak var button: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override class func awakeFromNib() {
super.awakeFromNib()
// Error - Instance member 'button' cannot be used on type 'CustomView'
button.addTarget(self, action: #selector(touchUpInside), for: .touchUpInside)
}
@objc func touchUpInside(_ sender: UIButton) {
print("Button clicked")
}
}
我已将源代码上传到 github。这是链接https://github.com/felixmariaa/AwakeFromNibTest/
这应该可以工作,我不确定出了什么问题。