【发布时间】:2020-11-11 03:13:39
【问题描述】:
我正在从一个名为 UIPillButton 的自定义 UIButton 类制作一个 SwiftUI 按钮。下面是创建 SwiftUI 按钮的代码:
Button(action: {
print("Button tapped")
}) {
PillButton()
.padding(.top)
}
这是我创建一个名为 PillButton 的 SwiftUI 视图的类,它将我的自定义 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>) {}
}
问题是如果我点击PillButton 本身,按钮不会运行该操作。仅当我选择PillButton 上方的缓冲区(填充)空间时才有效。我怎样才能做到这一点,以便我可以将自定义 PillButton 类用作普通的 SwiftUI 按钮?
【问题讨论】:
标签: ios button uibutton swiftui uiviewrepresentable