【发布时间】:2019-06-20 21:10:33
【问题描述】:
我做了一个简单的应用程序。我创建了一个 UIView 的子类,它提供了一个 UIButton。每当我点击按钮时,“数字”属性的值都会增加 1。我在 UIViewRepresentable 协议的帮助下将此自定义 UIView 集成到 SwiftUI 视图中。如何访问 SwiftUI 视图中的“数字”属性?
import UIKit
class CustomUIView: UIView {
var number = 0
override init(frame:CGRect) {
super.init(frame: frame)
createButton()
}
required init?(coder: NSCoder) {
fatalError("error")
}
private func createButton () {
let button = UIButton();
button.setTitle("Add", for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
self.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
@objc func buttonTapped(sender: UIButton) {
number += 1
print(number)
}
}
import SwiftUI
struct CustomButton: UIViewRepresentable {
func makeUIView(context: Context) -> CustomUIView {
let customButton = CustomUIView()
return customButton
}
func updateUIView(_ view: CustomUIView, context: Context) {
}
}
struct ContentView : View {
var body: some View {
NavigationView {
Text("I want to show here the value of the number property")
CustomButton().frame(height: 50)
}
}
}
【问题讨论】: