gpt4 book ai didi

ios - SwiftUI 中的选择器

转载 作者:行者123 更新时间:2023-11-29 13:55:13 24 4
gpt4 key购买 nike

我正在尝试使用在 SwiftUI 中为 UIKit 创建的第 3 方库,例如 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)

}
}

这段代码有两个错误:

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

最佳答案

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

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

关于ios - SwiftUI 中的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56867114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com