Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - proper use of @available() and #available

Tags:

xcode

ios

swiftui

Am I missing something in the following code?

This app builds (macOS Monterey b5 / Xcode 13 b5) and executes perfectly on an iOS 15 device -- but causes a SIGABRT on an iOS 14.7 device...

import SwiftUI

struct ContentView: View {
    @State private var text = "This app causes a runtime error on ios 14.7"
    @available(iOS 15.0, *)
    @FocusState var isInputActive: Bool

    var body: some View {

        if #available(iOS 15.0, *) {
            TextEditor(text: $text)
                .focused($isInputActive)
        } else {    //  ios14 or <
            TextEditor(text: $text)
        }

    }
}
like image 596
Koa Avatar asked Nov 15 '22 19:11

Koa


1 Answers

Was faced same issue and found solution by keeping property values in view modifier.

Here I give simple example :

@available(iOS 15.0, *)
struct TextEditor: ViewModifier {
    func body(content: Content) -> some View {
        
           content
           .font(.largeTitle)
           .foregroundColor(.white)
           .padding()
           .background(.blue)
        
    }
}

Then call as below :

if #available(iOS 15.0, *){
    Text("Hello world").modifier(TextEditor())
}
like image 85
Manish Avatar answered Jan 05 '23 07:01

Manish