在SwiftUI,Xcode 11.2中扩展TextField可点击区域

12

我无法弄清如何在SwiftUI(iOS 13,Xcode 11.2)中扩大可点击区域以打开键盘。我只能影响外观,而不能影响用户可以单击的实际区域(可点击区域 == 占位文本字体大小)。

在SwiftUI中创建TextField时,可以使用frame()来增加占位文本周围的大小,还可以使用fontsize使框内字体变得更大,但是没有什么方法可以在不使字体变得很大的情况下扩大可点击区域(即调出键盘的区域)。

//用于修改TextFields的代码

struct SignInModifier: ViewModifier {

func body(content: Content) -> some View {
    return content
        .padding(.all).font(.system(size: 18)).border(Color.purple).foregroundColor(Color.purple).shadow(radius: 2).frame(width: 350, height: 50)
    }
}

//在哪里调用修饰符

TextField("email address", text: $email).modifier(SignInModifier()).disableAutocorrection(true).keyboardType(.emailAddress)

我希望当你点击框架内的任何地方时,键盘可以弹出/你可以在文本字段中输入。但是,我需要点击占位文本的上部才能输入到文本字段中。

2个回答

0

有点小技巧,但是有效。

 struct ContentView: View {
 @State var name = ""
 @State var isFocused = false
  var body: some View {
    ZStack {
        HStack{
            Text(name)
                .font(.system(size: 50 , weight: .black))
                .foregroundColor(isFocused ? Color.clear : Color.black)
            Spacer()
        }
        TextField(name, text: $name , onEditingChanged: { editingChanged in
            isFocused = editingChanged
        }) 
        .font(.system(size: isFocused ? 50 :  100 , weight: .black))
        .foregroundColor(isFocused ? Color.black  : Color.clear)
        .frame(width: 300, height: isFocused ? 50 :  100 , alignment: .center)
                    .padding(.leading, isFocused ? 25 : 0  )
                    .padding(.trailing, isFocused ? 25 : 0 ) 
        .padding(.top,isFocused ? 25 : 0 )

        .padding(.bottom,isFocused ? 25 : 0 )
        
    }.frame(width: 300)
    .background(Color.red.opacity(0.3))
   }
    }

0

好的,所以我想出了一个解决方法,但并不完全是一个解决方案;只需将TextField嵌入按钮中,无论您在哪里单击,它都会立即打开


3
我无法确认在iOS 14.1上是否存在这种行为。 - Jonas W

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接