Arm1.ru

Tag: «swiftui»

How to get selected text inside of TextEditor in SwiftUI on macOS

How to get selected text inside of TextEditor in SwiftUI on macOS

TextEditor in SwiftUI still doesn’t have any API to get user selection. But since it’s using NSTextView internally we can subscribe to its notifications.

Here’s an example of getting a substring from user selection:

Читать далее...

comment comments
local_offer swiftui macos

Wrapping models in SwiftUI for Identifiable conformance

Using an array of models in List view in SwiftUI requires conformance to Identifiable protocol.

Here's an example of a model:

struct MyDataModel {
    let title: String
    let message: String
} 

An example of SwiftUI view that you want to display a list:

struct TestView: View {
    var dataArray: [MyDataModel]
    var body: some View {
        List(dataArray) { data in
            VStack {
                Text(data.title)
                Text(data.message)
            }
        }
    }
} 

Using MyDataModel in List will show an error in Xcode:

Xcode Identifiable conformance error

Sometimes you can't just change a model. It might be a data model from a third party SDK that you're using in your app. But you can create a wrapper for this struct to confirm Identifiable protocol:

struct MyDataModelWrapper: Identifiable {
    var id = UUID()
    var data: MyDataModel
}

let testDataModel = MyDataModel(
    title: "Title 1",
    message: "I wanna be used inside of a List"
)

let wrappedData = MyDataModelWrapper(data: testDataModel)

So the view will look like this:

struct TestView: View {
    var dataArray: [MyDataModelWrapper] 

    some View {
        List(dataArray) { wrappedData in
            VStack {
                Text(wrappedData.data.title)
                Text(wrappedData.data.message)
            }
        }
    }
}

Done.

comment comments