SwiftUI中的选择器。

12
我试图在SwiftUI中使用为UIKit创建的第三方库,例如BetterSegmentedControl库(https://github.com/gmarm/BetterSegmentedControl), 需要一个选择器来处理用户输入的objc函数。在SwiftUI中是否有处理这种情况的方法?
struct ContentView : UIViewRepresentable {
    func makeUIView(context: Context) -> BetterSegmentedControl {
        BetterSegmentedControl()
    }


    func updateUIView(_ view: BetterSegmentedControl, context: Context) {
        let control = BetterSegmentedControl(
            frame: CGRect(x: 0, y: 0, width: 300, height: 44),
            segments: LabelSegment.segments(withTitles: ["One", "Two", "Three"],
                                            normalTextColor: .lightGray,
                                            selectedTextColor: .white),
            index: 1,
            options: [.backgroundColor(.darkGray),
                      .indicatorViewBackgroundColor(.blue)])

        view.addSubview(control)

        @objc func controlValueChanged(_ sender: BetterSegmentedControl) {

        }

        control.addTarget(self, action: #selector(controlValueChanged(_:)), for: .valueChanged)
        view.addSubview(control)

    }
}

对于这段代码,有两个错误:

@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes


Argument of '#selector' cannot refer to local function 'controlValueChanged'

看看我的评论。完全正常。 - orkenstein
2个回答

10

我最终添加了一个辅助类:

struct MainView: View {

let helper = MainViewHelper()

// somewhere, sometimes...
vc.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self.helper, action: #selector(self.helper.closeAction))

}

class MainViewHelper {
  @objc func closeAction() {
    // whatever
  }
}

在类似的情况下,直到我将:NSObject添加到MainViewHelper中,它才对我起作用。 - Олександр Бабіч

1

好的,正如错误提示所述,您不能在结构体中使用objc。因此,我想您可以随时创建一个辅助类。

我在回答另一个问题时遇到了类似的问题,当监听键盘显示和隐藏通知时。这是我的答案。如果您向下滚动到KeyboardGuardian类,就会看到我在那里使用了objc。

这是一个起点...

https://dev59.com/FVMI5IYBdhLWcg3wUp42#56721268


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接