I have the following SwiftUI
view in my project that supports macOS 13+
and iOS 16+
:
struct MyTextField: View {
var placeholder: LocalizedStringKey
#if os (iOS)
var keyboardType: UIKeyboardType = .default
#endif
}
at call site I can’t use a single initializer like this for both operating systems:
MyTextField(placeholder: "some placeholder",
keyboardType: .asciiCapableNumberPad,
hasToolbar: true)
as it gives a syntax error for macOS
as it cannot find the keyboardType
argument in the init signature, I know that I can check for the os at call site using #if os(iOS)
and provide different init for the target os, but it’s cumbersome when I have a huge form of text fields where I should determine the keyboard type for every text field, is there a way to call one init at call site to support the 2 operating systems in this case ?
2
Answers
Create your custom enum class with the
UIKeyboardType
s.And use it in your initializer:
If
MyTextField
wraps a normal SwiftUITextField
, then you don’t need to passkeyboardType
as a parameter. You can use the existingkeyboardType
modifier, like this:The
keyboardType
modifier applies to all descendants of theMyTextField
.