2

我正在从一个名为UIPillButton. 下面是创建 SwiftUI 按钮的代码:

Button(action: {
    print("Button tapped")
}) {
    PillButton()
        .padding(.top)
}

这是我创建 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>) {}
}

问题是如果我点击按钮本身,按钮不会运行该操作PillButton。仅当我选择PillButton. 我怎样才能做到这一点,以便我可以将自定义PillButton类用作普通的 SwiftUI 按钮?

截屏

4

1 回答 1

2

目前尚不清楚是什么NTPillButton,但如果它是子类,UIButton那么下面的通用方法演示(使用 base UIButton)应该清楚且适用。

使用 Xcode 11.4 / iOS 13.4 测试

下面给出了这个简单的用法

    PillButton(title: "Start Test") {
        print("Button tapped")
    }
    .frame(maxWidth: .infinity)       // << screen-wide
    .padding(.top)

所以现在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) {}
}
于 2020-07-21T17:27:44.930 回答