Cal*_*cki 5 button uibutton ios swiftui uiviewrepresentable
我正在从一个名为 的自定义 UIButton 类制作一个 SwiftUI 按钮UIPillButton。以下是创建 SwiftUI 按钮的代码:
Button(action: {
print("Button tapped")
}) {
PillButton()
.padding(.top)
}
Run Code Online (Sandbox Code Playgroud)
这是我的类,用于创建一个名为 SwiftUI 视图的类,PillButton该视图将我的自定义 UIButton 转换为:
struct PillButton: UIViewRepresentable {
var ntPillButton = NTPillButton(type: .filled, title: "Start Test")
func makeCoordinator() -> Coordinator { Coordinator(self) }
class Coordinator: NSObject {
var parent: PillButton
init(_ pillButton: PillButton) {
self.parent = pillButton
super.init()
}
}
func makeUIView(context: UIViewRepresentableContext<PillButton>) -> UIView {
let view = UIView()
view.addSubview(ntPillButton)
NSLayoutConstraint.activate([
ntPillButton.leadingAnchor.constraint(equalTo: view.leadingAnchor),
ntPillButton.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
return view
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PillButton>) {}
}
Run Code Online (Sandbox Code Playgroud)
问题是,如果我点击按钮本身,按钮不会运行该操作PillButton。仅当我选择 .txt 上方的缓冲区(填充)空间时,它才有效PillButton。我怎样才能将自定义PillButton类用作普通的 SwiftUI 按钮?
目前尚不清楚是什么NTPillButton,但如果它是 的子类,UIButton那么以下通用方法的演示(使用 base UIButton)应该清晰且适用。
使用 Xcode 11.4 / iOS 13.4 进行测试
下面给出了这个简单的用法
PillButton(title: "Start Test") {
print("Button tapped")
}
.frame(maxWidth: .infinity) // << screen-wide
.padding(.top)
Run Code Online (Sandbox Code Playgroud)
现在PillButton演示一下:
struct PillButton: UIViewRepresentable {
let title: String
let action: () -> ()
var ntPillButton = UIButton()//NTPillButton(type: .filled, title: "Start Test")
func makeCoordinator() -> Coordinator { Coordinator(self) }
class Coordinator: NSObject {
var parent: PillButton
init(_ pillButton: PillButton) {
self.parent = pillButton
super.init()
}
@objc func doAction(_ sender: Any) {
self.parent.action()
}
}
func makeUIView(context: Context) -> UIButton {
let button = UIButton(type: .system)
button.setTitle(self.title, for: .normal)
button.addTarget(context.coordinator, action: #selector(Coordinator.doAction(_ :)), for: .touchDown)
return button
}
func updateUIView(_ uiView: UIButton, context: Context) {}
}
Run Code Online (Sandbox Code Playgroud)