I’m working on an app where I need to let the user enter ip addresses. I was wondering if there is a SwiftUI IP address entry view? Or I guess a UIKit control would work.
Thanks
I’m working on an app where I need to let the user enter ip addresses. I was wondering if there is a SwiftUI IP address entry view? Or I guess a UIKit control would work.
Thanks
This is possible both in SwiftUI and UIKit. I’m assuming you are looking for a sample, so here goes a simple one that you can use as a starting block. It creates a form that doesn’t “submit” until the entry is valid:
import SwiftUI
struct ContentView: View {
@State var address = ""
var body: some View {
NavigationView {
Form {
Section {
TextField("IP", text: $address)
}
Section {
NavigationLink {
Text("Done!")
} label: {
Text("Continue")
}
}
.disabled(hasValidAddress == false)
}
.navigationTitle("Some Form")
.navigationBarTitleDisplayMode(.large)
}
}
var hasValidAddress: Bool {
var socketAddress = sockaddr_in()
return address.withCString({ cstring in inet_pton(AF_INET, cstring, &socketAddress.sin_addr) }) == 1
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The code you are looking for is in the computed property hasValidAddress, which attempts to convert an IP from string to a number (32 bit), if it success, the IPv4 is valid.
Note how it disables the navigation link until it has a valid address.
That’s a good idea. Thanks
This topic was automatically closed after 166 days. New replies are no longer allowed.