我正在尝试使用在 SwiftUI 中为 UIKit 创建的 3rd 方库,例如,该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)
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码有两个错误:
@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'
Run Code Online (Sandbox Code Playgroud)
我最终添加了一个助手类:
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
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,正如错误告诉您的那样,您不能在结构上使用 objc。所以我想你总是可以创建一个辅助类。
在另一个问题中收听键盘显示和隐藏通知时,我遇到了类似的问题。这是我的答案。如果您向下滚动到 KeyboardGuardian 类,您会看到我在那里使用 objc。
这是一个起点...
归档时间: |
|
查看次数: |
2570 次 |
最近记录: |