SwiftUI Picker onChange或等效版本?

时间:2019-08-16 04:19:12

标签: swiftui

我想在$(document).on("change", 'select#recordavailable', function(e) { var dateInquiry = $(this).val(); $.ajax ({ type: "GET", data: 'dateInquiry='+dateInquiry, url: 'getmysqldata', dataType: 'JSON', success: function(data) { var randomnumber = Math.floor((Math.random()*100)+1); var winPrint = window.open('',"",'PopUp'+randomnumber+', "scrollbars=1,menubar=0,resizable=1"'); winPrint.document.write('<title>Display Record of '+dateInquiry+'</title><style>table{ border-collapse: collapse;border-spacing: 0;'+ 'width: 100%;border: 1px solid #ddd;}table, td, th{border: 1px solid black;text-align:center;padding: 5px;}#stockname {text-align: left;}'+ 'h3 {text-align:center;}#qty, #cost, #balance, #total {text-align: right;}</style><h3>'+dateInquiry+'</h3>'); winPrint.document.write(JSON.stringify(data)); } }); }); 被更改但没有@State且无法将Picker置于选择器状态时更改其他一些不相关的onChanged变量那我还能怎么做呢?

9 个答案:

答案 0 :(得分:55)

这就是我刚刚决定使用的... (部署目标iOS 13)

struct MyPicker: View {
    @State private var favoriteColor = 0

    var body: some View {
        Picker(selection: $favoriteColor.onChange(colorChange), label: Text("Color")) {
            Text("Red").tag(0)
            Text("Green").tag(1)
            Text("Blue").tag(2)
        }
    }

    func colorChange(_ tag: Int) {
        print("Color tag: \(tag)")
    }
}

使用此助手

extension Binding {
    func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> {
        return Binding(
            get: { self.wrappedValue },
            set: { selection in
                self.wrappedValue = selection
                handler(selection)
        })
    }
}

编辑:

如果您的部署目标设置为iOS 14或更高版本-苹果提供了onChange的内置View扩展名,可以这样使用(谢谢@杰里米):

Picker(selection: $favoriteColor, label: Text("Color")) {
    // ..
}
.onChange(of: favoriteColor) { print("Color tag: \($0)") }

答案 1 :(得分:15)

我认为这是更简单的解决方案:

@State private var pickerIndex = 0
var yourData = ["Item 1", "Item 2", "Item 3"]

// USE this if needed to notify parent
@Binding var notifyParentOnChangeIndex: Int    

var body: some View {

   let pi = Binding<Int>(get: {

            return self.pickerIndex

        }, set: {

            self.pickerIndex = $0

            // TODO: DO YOUR STUFF HERE
            // TODO: DO YOUR STUFF HERE
            // TODO: DO YOUR STUFF HERE

            // USE this if needed to notify parent
            self.notifyParentOnChangeIndex = $0

        })

   return VStack{

            Picker(selection: pi, label: Text("Yolo")) {
                ForEach(self.yourData.indices) {
                    Text(self.yourData[$0])
                }
            }
            .pickerStyle(WheelPickerStyle())
            .padding()

   }

}

答案 2 :(得分:6)

我知道这是一岁的帖子,但是我认为此解决方案可能会帮助其他需要解决方案的来访者。希望它可以帮助其他人。

import Foundation
import SwiftUI

struct MeasurementUnitView: View {
    
    @State var selectedIndex = unitTypes.firstIndex(of: UserDefaults.standard.string(forKey: "Unit")!)!
    var userSettings: UserSettings
    
    var body: some View {
        
        VStack {
            Spacer(minLength: 15)
            Form {
                Section {
                    Picker(selection: self.$selectedIndex, label: Text("Current UnitType")) {
                        
                        ForEach(0..<unitTypes.count, id: \.self) {
                            Text(unitTypes[$0])
                        }
                    }.onReceive([self.selectedIndex].publisher.first()) { (value) in
                        self.savePick()
                    }
                    .navigationBarTitle("Change Unit Type", displayMode: .inline)
                }
            }
        }
    }
    
    func savePick() {
        
        if (userSettings.unit != unitTypes[selectedIndex]) {
            userSettings.unit = unitTypes[selectedIndex]
        }
    }
}


答案 3 :(得分:6)

首先,充分感谢ccwasden以获得最佳答案。我必须对其稍作修改以使其对我有用,所以我在回答这个问题,希望其他人也能找到它。

这就是我最终的结果(在iOS 14 GM和Xcode 12 GM上进行了测试)

struct SwiftUIView: View {
    @State private var selection = 0

    var body: some View {
        Picker(selection: $selection, label: Text("Some Label")) {
            ForEach(0 ..< 5) {
                Text("Number \($0)") }
        }.onChange(of: selection) { _ in
            print(selection)
        }
        
    }
}

我需要包含“ _ in”。没有它,我收到错误消息“无法将类型'Int'的值转换为预期的参数类型'()'”

答案 4 :(得分:5)

我使用分段选择器,并且有类似的要求。在尝试了几件事之后,我只使用了一个同时具有ObservableObjectPublisherPassthroughSubject发布者作为选择的对象。这让我很满意SwiftUI,并且使用onReceive()也可以做其他事情。

// Selector for the base and radix
Picker("Radix", selection: $base.value) {
    Text("Dec").tag(10)
    Text("Hex").tag(16)
    Text("Oct").tag(8)
}
.pickerStyle(SegmentedPickerStyle())
// receiver for changes in base
.onReceive(base.publisher, perform: { self.setRadices(base: $0) })

基地有一个objectWillChange和一个PassthroughSubject<Int, Never>的发布者,它们被形象地称为发布者。

class Observable<T>: ObservableObject, Identifiable {
    let id = UUID()
    let objectWillChange = ObservableObjectPublisher()
    let publisher = PassthroughSubject<T, Never>()
    var value: T {
        willSet { objectWillChange.send() }
        didSet { publisher.send(value) }
    }

    init(_ initValue: T) { self.value = initValue }
}

typealias ObservableInt = Observable<Int>

定义objectWillChange并不是绝对必要的,但是当我写这封信时,我想提醒自己它在那里。

答案 5 :(得分:2)

SwiftUI 1和2

使用onReceiveJust

import Combine
import SwiftUI

struct ContentView: View {
    @State private var selection = 0

    var body: some View {
        Picker("Some Label", selection: $selection) {
            ForEach(0 ..< 5, id: \.self) {
                Text("Number \($0)")
            }
        }
        .onReceive(Just(selection)) {
            print("Selected: \($0)")
        }
    }
}

答案 6 :(得分:2)

对于必须同时支持iOS 13和14的用户,我添加了一个扩展名,该扩展名对这两者均适用。不要忘记导入Combine。

Extension View {
    @ViewBuilder func onChangeBackwardsCompatible<T: Equatable>(of value: T, perform completion: @escaping (T) -> Void) -> some View {
        if #available(iOS 14.0, *) {
            self.onChange(of: value, perform: completion)
        } else {
            self.onReceive([value].publisher.first()) { (value) in
                completion(value)
            }
        }
    }
}

用法:

Picker(selection: $selectedIndex, label: Text("Color")) {
    Text("Red").tag(0)
    Text("Blue").tag(1)
}.onChangeBackwardsCompatible(of: selectedIndex) { (newIndex) in
    print("Do something with \(newIndex)")
}

重要说明::如果要更改完成块中观察到的对象内的已发布属性,此解决方案将在iOS 13中引起无限循环。但是,通过添加检查可以很容易地解决此问题。 ,就像这样:

.onChangeBackwardsCompatible(of: showSheet, perform: { (shouldShowSheet) in
   if shouldShowSheet {
      self.router.currentSheet = .chosenSheet
      showSheet = false
   }
})

答案 7 :(得分:2)

具有关系的 iOS 14 和 CoreData 实体

我在尝试绑定到 CoreData 实体时遇到了这个问题,发现以下方法有效:

Picker("Level", selection: $contact.level) {
                        ForEach(levels) { (level: Level?) in
                            HStack {
                                Circle().fill(Color.green)
                                    .frame(width: 8, height: 8)
                                Text("\(level?.name ?? "Unassigned")")
                            }
                            .tag(level)
                        }
                    }
.onChange(of: contact.level) { _ in savecontact() }

其中“联系人”是与“级别”有关系的实体。

Contact 类是一个 @ObservedObject var contact: Contact

saveContact 是一个 do-catch 函数,用于 try viewContext.save()...

答案 8 :(得分:0)

非常重要的问题:我们必须将一些东西传递给 Picker 项目视图(在 ForEach 内部)的“标记”修饰符,以让它“识别”项目并触发选择更改事件。并且我们传递的值将通过 Picker 的“选择”返回到 Binding 变量中。

例如:

Picker(selection: $selected, label: Text("")){
            
            ForEach(data){item in //data's item type must conform Identifiable
                
                HStack{
                    
                    //item view
                    
                
                }
                .tag(item.property)
                
            }
            
        }
        
        .onChange(of: selected, perform: { value in
            
            //handle value of selected here (selected = item.property when user change selection)
            
        })