So I am trying to build a custom look to a Text Input in SwiftUI.
I have attempting to do this with a few different tricks, and the one I came up with was using labels and i was going to hide a TextInput behind the labels and let it basically act like a textinput without actually being a text input.
I dont even know if this is possible. If not I need to go back to the drawing board.
This is what I want it to look like blank
Black numbers, with the custom spacing and font etc.
Once numbers start to be entered they turn white.
however as you can see, the textInput is visible. Is it possible to hide it?
import SwiftUI
struct CustomInput: View {
#State var id: String = " "
#State var label1: Character = Character(" ")
#State var label2: Character = Character(" ")
#State var label3: Character = Character(" ")
#State var label4: Character = Character(" ")
#State var label5: Character = Character(" ")
#State var label6: Character = Character(" ")
#State var label7: Character = Character(" ")
#State var label8: Character = Character(" ")
#State var label9: Character = Character(" ")
var body: some View {
ZStack {
Color.green
HStack(spacing: 15){
ForEach(0 ..< 9) { index in
Text(String(id[safe: index] ?? "0"))
.font(.custom("regular", size: 32))
.frame(height: 48)
.foregroundColor(id.count <= index ? .black : .white)
}
}
.frame(width: 311, height: 48)
TextField("", text: $id)
.frame(width: 311, height: 48)
}
.frame(width: 311, height: 48)
}
}
extension StringProtocol {
subscript(safe offset: Int) -> Character? {
guard 0 ..< count ~= offset else {
return nil
}
return self[index(startIndex, offsetBy: offset)]
}
}
Here is a workable solution for you to continue off of. Honestly your best bet is to probably use a UIViewRepresentable but I'll leave that up to you.
NOTE: You'll need to handle a few things here. It'll need a few possible errors to be handled.
Bug if you attempt to use a character, non-digit.
Disable Context Menu actions (Copy, Paste, etc..) I hid it by setting accent to .clear
Add your styling.
struct FirstView: View {
#State var numbers = [0, 0, 0, 0, 0, 0, 0, 0, 0]
#State var editedNumbers = ""
var body: some View {
ZStack {
HStack {
ForEach(0..<numbers.count) { index in
Text(String(numbers[index]))
.padding(.horizontal, 2)
.foregroundColor(numbers[index] != 0 ? .white : .black)
}
}
.frame(width: UIScreen.main.bounds.width * 0.8)
.padding(.vertical)
.background(Color.green)
TextField("", text: $editedNumbers)
.frame(width: UIScreen.main.bounds.width * 0.8)
.padding(.vertical)
.foregroundColor(.clear)
.accentColor(.clear)
.onChange(of: editedNumbers, perform: { value in
numbers = [0, 0, 0, 0, 0, 0, 0, 0, 0]
for (index, char) in editedNumbers.enumerated() {
if index >= 0 && index <= 8 {
numbers[index] = char.wholeNumberValue ?? 0
}
}
})
}
}
}
Related
I’m working on a dilution calculator. I have it 98% working, however, I want it to work a certain way and I’m not sure to do that. This is my first app so I’m new at this.
So I want the user to be able to input the numbers and hit a button to get the calculation. I’ve been using #State and through my research and understanding, using that instantly updates any changes the user makes.
So how do I go about making the app wait till the user hits the “Go” button.
Hers my code so far.
#State private var ContainerSize = 0
#State private var DilutionRatio = 0
#State private var Go = ""
#State private var TotalProduct = 0.0
#State private var TotalWater = 0.0
#FocusState private var amountIsFocused: Bool
var totalProductAmount: Double {
let firstValue = Double(ContainerSize)
let secondValue = Double(DilutionRatio + 1)
let totalProduct = Double(firstValue / secondValue)
return totalProduct
}
var totalWaterAmount: Double {
let firstValue = Double(ContainerSize)
let secondValue = Double(DilutionRatio + 1)
let totalWater = Double(firstValue - secondValue)
return totalWater
}
//Container Size
ZStack {
Image("Container Size (Oz)")
.padding(.vertical, -15)
TextField("", value: $ContainerSize, format: .number)
.frame(width: 200.0, height: 60.0)
.multilineTextAlignment(.center)
.font(Font.system(size: 50, design: .default))
.keyboardType(.decimalPad)
.focused($amountIsFocused)
}
}
//Dilution Ratio
ZStack {
Image("Dilution Ratio - 2")
.padding(.vertical, -10)
TextField("", value: $DilutionRatio, format: .number)
.frame(width: 200.0, height: 60.0)
.multilineTextAlignment(.center)
.font(Font.system(size: 50, design: .default))
.keyboardType(.decimalPad)
.focused($amountIsFocused)
}
//Go Button
Button(action: {}, label: {
Image("Go Button")
})
//Results
HStack{
ZStack {
Image("Total Product (Oz)")
Text("\(totalProductAmount, specifier: "%.1f")")
.font(Font.system(size: 60, design: .default))
}
ZStack {
Image("Total Water (Oz)")
Text(totalWaterAmount, format: .number)
.font(Font.system(size: 60, design: .default))
}
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer(
Button("Done") {
amountIsFocused = false
}
}
struct CalculatorIView_Previews: PreviewProvider {
static var previews: some View {
CalculatorIView()
}
}
The calculator works as is but I want the user to input numbers, hit the “Go” button, and the results are shown.
You can create func for calculation and call it from button action. You should remove calculated properties, var totalProductAmount: Double and var totalWaterAmount: Double and do the calculation inside the function. You can check the example below.
https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-a-tappable-button
var body: some View{
Button(action: {
someCalculation()
}, label: {
Image("Go Button")
})
}
func someCalculation(){
// do some calculation and you can set #State variables or you can return some value. For example 'func someCalculation()->Double'
}
So far you do the calculation in calculated properties and display them directly. So they'll update every time one of their underlying #State values change.
If you only want to show results on button press, you should display your #State result vars, and update inside the button action.
Side note: property names should start lowercase.
struct ContentView: View {
// side note: var names should start lowerCase
#State private var containerSize = 0
#State private var dilutionRatio = 0
#State private var totalProduct = 0.0
#State private var totalWater = 0.0
// for clarity change calculations to funcs
func totalProductAmount() -> Double {
let firstValue = Double(containerSize)
let secondValue = Double(dilutionRatio + 1)
let totalProduct = Double(firstValue / secondValue)
return totalProduct
}
func totalWaterAmount() -> Double {
let firstValue = Double(containerSize)
let secondValue = Double(dilutionRatio + 1)
let totalWater = Double(firstValue - secondValue)
return totalWater
}
var body: some View {
VStack {
//Container Size
Text("Container Size (Oz)")
.padding(.vertical, -15)
TextField("", value: $containerSize, format: .number)
.frame(width: 200.0, height: 60.0)
.multilineTextAlignment(.center)
.font(Font.system(size: 50, design: .default))
.keyboardType(.decimalPad)
//Dilution Ratio
Text("Dilution Ratio - 2")
.padding(.vertical, -10)
TextField("", value: $dilutionRatio, format: .number)
.frame(width: 200.0, height: 60.0)
.multilineTextAlignment(.center)
.font(Font.system(size: 50, design: .default))
.keyboardType(.decimalPad)
//Go Button
Button(action: {
// Calculate here, and set State vars with results
totalProduct = totalProductAmount()
totalWater = totalWaterAmount()
}, label: {
Text("Go Button")
})
.buttonStyle(.borderedProminent)
.padding()
//Results
// Show the state vars, not the calculation vars!
HStack{
VStack {
Text("Total Product (Oz)")
Text("\(totalProduct, specifier: "%.1f")")
.font(Font.system(size: 60, design: .default))
}
VStack {
Text("Total Water (Oz)")
Text(totalWater, format: .number)
.font(Font.system(size: 60, design: .default))
}
}
}
}
}
I'm trying to use a LazyVGrid in SwiftUI where you can touch and drag your finger to select multiple adjacent cells in a specific order. This is not a drag and drop and I don't want to move the cells (maybe drag isn't the right term here, but couldn't think of another term to describe it). Also, you would be able to reverse the selection (ie: each cell can only be selected once and reversing direction would un-select the cell). How can I accomplish this? Thanks!
For example:
struct ContentView: View {
#EnvironmentObject private var cellsArray: CellsArray
var body: some View {
VStack {
LazyVGrid(columns: gridItems, spacing: spacing) {
ForEach(0..<(rows * columns), id: \.self){index in
VStack(spacing: 0) {
CellsView(index: index)
}
}
}
}
}
}
struct CellsView: View {
#State var index: Int
#EnvironmentObject var cellsArray: CellsArray
var body: some View {
ZStack {
Text("\(self.cellsArray[index].cellValue)") //cellValue is a string
.foregroundColor(Color.yellow)
.frame(width: getWidth(), height: getWidth())
.background(Color.gray)
}
//.onTapGesture ???
}
func getWidth()->CGFloat{
let width = UIScreen.main.bounds.width - 10
return width / CGFloat(columns)
}
}
Something like this might help, the only issue here is the coordinate space. Overlay is not drawing the rectangle in the correct coordinate space.
struct ImagesView: View {
var columnSize: CGFloat
#Binding var projectImages: [ProjectImage]
#State var selectedImages: [ImageSelection] = []
#State var dragWidth: CGFloat = 1.0
#State var dragHeight: CGFloat = 1.0
#State var dragStart: CGPoint = CGPoint(x:0, y:0)
let columns = [
GridItem(.adaptive(minimum: 200), spacing: 0)
]
var body: some View {
GeometryReader() { geometry in
ZStack{
ScrollView{
LazyVGrid(columns: [
GridItem(.adaptive(minimum: columnSize), spacing: 2)
], spacing: 2){
ForEach(projectImages, id: \.imageUUID){ image in
Image(nsImage: NSImage(data: image.imageData)!)
.resizable()
.scaledToFit()
.border(selectedImages.contains(where: {imageSelection in imageSelection.uuid == image.imageUUID}) ? Color.blue : .primary, width: selectedImages.contains(where: {imageSelection in imageSelection.uuid == image.imageUUID}) ? 5.0 : 1.0)
.gesture(TapGesture(count: 2).onEnded{
print("Double tap finished")
})
.gesture(TapGesture(count: 1).onEnded{
if selectedImages.contains(where: {imageSelection in imageSelection.uuid == image.imageUUID}) {
print("Image is already selected")
if let index = selectedImages.firstIndex(where: {imageSelection in imageSelection.uuid == image.imageUUID}){
selectedImages.remove(at: index)
}
} else {
selectedImages.append(ImageSelection(imageUUID: image.imageUUID))
print("Image has been selected")
}
})
}
}
.frame(minHeight: 50)
.padding(.horizontal, 1)
}
.simultaneousGesture(
DragGesture(minimumDistance: 2)
.onChanged({ value in
print("Drag Start: \(value.startLocation.x)")
self.dragStart = value.startLocation
self.dragWidth = value.translation.width
self.dragHeight = value.translation.height
})
)
.overlay{
Rectangle()
.frame(width: dragWidth, height: dragHeight)
.offset(x:dragStart.x, y:dragStart.y)
}
}
}
}
}
I am a real newbie in swift, but I am stuck at this problem...
I am building a picker to change an optical prescription, but I am not able to change SPH and CYL values (doubles), while AX works good. Any help?
Also the way that text comes out, I tried to add .format modifier just to show 2 decimals, but still no luck.
Thanks!
import SwiftUI
struct ContentView: View {
#State var selectedsph = 0.0
#State var selectedcyl = 0.0
#State var selectedax = 0
var sph : [Double] = Array(stride(from: -20.00, through: 20.00, by: 0.25))
var cyl : [Double] = Array(stride(from: -10.00, through: 10.00, by: 0.25))
var ax = [Int](0...180)
var body: some View {
GeometryReader { geometry in
VStack {
Spacer()
HStack(spacing:0) {
Picker(selection: self.$selectedsph, label: Text("")) {
ForEach(0 ..< self.sph.count) { index in
Text("Sph " + "\(self.sph[index])").tag(index)
}
}
.pickerStyle(.wheel)
.frame(width: geometry.size.width/3, height: 150)
.compositingGroup()
.clipped()
Picker(selection: self.$selectedcyl, label: Text("Picker")) {
ForEach(0 ..< self.cyl.count) { index in
Text("Cyl " + "\(self.cyl[index])").tag(index)
}
}
.pickerStyle(.wheel)
.frame(width: geometry.size.width/3.5, height: 150)
.compositingGroup()
.clipped()
Picker(selection: self.$selectedax, label: Text("Picker")) {
ForEach(0 ..< self.ax.count) { index in
Text("AX " + "\(self.ax[index])").tag(index)
}
}
.pickerStyle(.wheel)
.frame(width: geometry.size.width/3, height: 150)
.compositingGroup()
.clipped()
}.padding()
}
HStack(alignment: .center) {
Text("Occhio Destro: SF: \(selectedsph) Cyl: \(selectedcyl) Ax: \(selectedax)")
.fontWeight(.medium).multilineTextAlignment(.center).padding(.all)
}
Spacer()
}
}
}
The picker values are the indices of the selected values. Change your #State vars to hold Int:
#State var selectedsph = 0
#State var selectedcyl = 0
#State var selectedax = 0
And change your Text to use the indices to look up the values. Add specifier: "%.2f" to show just 2 decimal places:
Text("Occhio Destro: SF: \(sph[selectedsph], specifier: "%.2f") Cyl: \(cyl[selectedcyl], specifier: "%.2f") Ax: \(ax[selectedax])")
.fontWeight(.medium).multilineTextAlignment(.center).padding(.all)
I am trying to create an OTP page for my app but I don't know how to make the next textfield focus after I input a single digit in the first text field.
I created 6 text field for each digit of OTP. The next text field should be the first responder once I key in one digit from the first text field and so forth untill all 6 digits are complete.
I'm not sure how to do that in Swift UI. So far I manage to create 6 lines only as seen in the screenshot. The expected is only one digit should be per line. So the next text field should be focus once I input a single integer.
I tried other post like the use of #FocusState but it says unknown attribute.
I also tried the custom text field How to move to next TextField in SwiftUI?
but I cannot seem to make it work.
import SwiftUI
struct ContentView: View {
#State private var OTP1 = ""
#State private var OTP2 = ""
#State private var OTP3 = ""
#State private var OTP4 = ""
#State private var OTP5 = ""
#State private var OTP6 = ""
var body: some View {
VStack {
HStack(spacing: 16) {
VStack {
TextField("", text: $OTP1)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
VStack {
TextField("", text: $OTP2)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
VStack {
TextField("", text: $OTP3)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
VStack {
TextField("", text: $OTP4)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
VStack {
TextField("", text: $OTP5)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
VStack {
TextField("", text: $OTP6)
Line()
.stroke(style: StrokeStyle(lineWidth: 1))
.frame(width: 41, height: 1)
}
}
}
}
}
struct Line: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: rect.width, y: 0))
return path
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewLayout(.fixed(width: 560, height: 50))
}
}
My OTP Page
Expected field
Here is my answer for iOS 14.
The view.
struct ContentView: View {
#StateObject var viewModel = ViewModel()
#State var isFocused = false
let textBoxWidth = UIScreen.main.bounds.width / 8
let textBoxHeight = UIScreen.main.bounds.width / 8
let spaceBetweenBoxes: CGFloat = 10
let paddingOfBox: CGFloat = 1
var textFieldOriginalWidth: CGFloat {
(textBoxWidth*6)+(spaceBetweenBoxes*3)+((paddingOfBox*2)*3)
}
var body: some View {
VStack {
ZStack {
HStack (spacing: spaceBetweenBoxes){
otpText(text: viewModel.otp1)
otpText(text: viewModel.otp2)
otpText(text: viewModel.otp3)
otpText(text: viewModel.otp4)
otpText(text: viewModel.otp5)
otpText(text: viewModel.otp6)
}
TextField("", text: $viewModel.otpField)
.frame(width: isFocused ? 0 : textFieldOriginalWidth, height: textBoxHeight)
.disabled(viewModel.isTextFieldDisabled)
.textContentType(.oneTimeCode)
.foregroundColor(.clear)
.accentColor(.clear)
.background(Color.clear)
.keyboardType(.numberPad)
}
}
}
private func otpText(text: String) -> some View {
return Text(text)
.font(.title)
.frame(width: textBoxWidth, height: textBoxHeight)
.background(VStack{
Spacer()
RoundedRectangle(cornerRadius: 1)
.frame(height: 0.5)
})
.padding(paddingOfBox)
}
}
This is the viewModel.
class ViewModel: ObservableObject {
#Published var otpField = "" {
didSet {
guard otpField.count <= 6,
otpField.last?.isNumber ?? true else {
otpField = oldValue
return
}
}
}
var otp1: String {
guard otpField.count >= 1 else {
return ""
}
return String(Array(otpField)[0])
}
var otp2: String {
guard otpField.count >= 2 else {
return ""
}
return String(Array(otpField)[1])
}
var otp3: String {
guard otpField.count >= 3 else {
return ""
}
return String(Array(otpField)[2])
}
var otp4: String {
guard otpField.count >= 4 else {
return ""
}
return String(Array(otpField)[3])
}
var otp5: String {
guard otpField.count >= 5 else {
return ""
}
return String(Array(otpField)[4])
}
var otp6: String {
guard otpField.count >= 6 else {
return ""
}
return String(Array(otpField)[5])
}
#Published var borderColor: Color = .black
#Published var isTextFieldDisabled = false
var successCompletionHandler: (()->())?
#Published var showResendText = false
}
Not very reusable but it works....
If you want to change the length don't forget to update the viewModel's otpField's didSet and the views textFieldOriginalWidth.
The idea here is to hide the TextField and make it seem like the user is typing in the boxes.
An Idea could be to shrink the TextField when user is typing by using the isEditing closure from the TextField. You would want to shrink it so the user can't paste text or get that "popup" or the textfield cursor.
I have a movable VStack which carry a Picker. When I want chose deferent option from Picker I cannot, because SwiftUI thinks I want use DragGesture, therefor my Picker is lockdown! My DragGesture has minimumDistance: 0 but it does not solve issue when I change this value also, from other hand I like to have minimumDistance: 0 so it is not even an option for me to solving issue with increasing minimumDistance, so I need help to find a way, thanks.
struct ContentView: View {
var body: some View {
StyleView()
}
}
struct StyleView: View {
#State private var location: CGSize = CGSize()
#GestureState private var translation: CGSize = CGSize()
#State private var styleIndex: Int = 0
let styles: [String] = ["a", "b", "c"]
var body: some View {
VStack {
Picker(selection: $styleIndex, label: Text("Style")) {
ForEach(styles.indices, id:\.self) { index in
Text(styles[index].description)
}
}
.pickerStyle(SegmentedPickerStyle())
.padding()
Text("selected style: " + styles[styleIndex])
}
.padding()
.background(Color.red)
.cornerRadius(10)
.padding()
.position(x: location.width + translation.width + 200, y: location.height + translation.height + 100)
.gesture(DragGesture(minimumDistance: 0)
.updating($translation) { value, state, _ in
state = value.translation
}
.onEnded { value in
location = CGSize(width: location.width + value.translation.width, height: location.height + value.translation.height)
})
}
}
DragGesture triggers when the user presses down on a view and move at least a certain distance away. So, this creates a picker with a drag gesture that triggers when the user moves it at least 10 points (it should be greater than 0 otherwise how can it know about the tap and the drag)
struct StyleView: View {
#State private var location: CGSize = CGSize()
#GestureState private var translation: CGSize = CGSize()
#State private var styleIndex: Int = 0
let styles: [String] = ["a", "b", "c"]
var body: some View {
VStack {
Picker(selection: $styleIndex, label: Text("Style")) {
ForEach(styles.indices, id:\.self) { index in
Text(styles[index].description)
}
}.gesture(DragAndTapGesture(count: styles.count, selected: $styleIndex).horizontal)
.pickerStyle(SegmentedPickerStyle())
.padding()
Text("selected style: " + styles[styleIndex])
}
.padding()
.background(Color.red)
.cornerRadius(10)
.padding()
.position(x: location.width + translation.width + 200, y: location.height + translation.height + 100)
.gesture(DragGesture(minimumDistance: 1)
.updating($translation) { value, state, _ in
state = value.translation
}
.onEnded { value in
location = CGSize(width: location.width + value.translation.width, height: location.height + value.translation.height)
})
}
}
struct DragAndTapGesture {
var count: Int
#Binding var selected: Int
init(count: Int, selected: Binding<Int>) {
self.count = count
self._selected = selected
}
var horizontal: some Gesture {
DragGesture().onEnded { value in
if -value.predictedEndTranslation.width > UIScreen.main.bounds.width / 2, self.selected < self.count - 1 {
self.selected += 1
}
if value.predictedEndTranslation.width > UIScreen.main.bounds.width / 2, self.selected > 0 {
self.selected -= 1
}
}
}
}