【问题标题】:Selectors in SwiftUISwiftUI 中的选择器
【发布时间】:2019-11-13 23:11:29
【问题描述】:

我正在尝试使用为 SwiftUI 中的 UIKit 创建的第三方库,例如 BetterSegmentedControl 库 (https://github.com/gmarm/BetterSegmentedControl) 需要一个 Selector 女巫采用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)

    }
}

此代码有 2 个错误:

@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'

【问题讨论】:

  • 查看我的评论。工作得很好

标签: ios swiftui


【解决方案1】:

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

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
  }
}

【讨论】:

    【解决方案2】:

    好吧,正如错误告诉你的那样,你不能在结构上使用 objc。所以我猜你总是可以创建一个帮助类。

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

    这是一个起点……

    https://stackoverflow.com/a/56721268/7786555

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多