使 TextField 将其内容包装在 SwiftUI 中 [英] Make TextField wrap it content in SwiftUI

查看:31
本文介绍了使 TextField 将其内容包装在 SwiftUI 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现这样的组件

TextField (5 000) 和 Text (PLN) 一起应该水平居中.输入新数字时,应取消文本 (PLN).我想我必须将这两个视图合并到一个容器中并居中,例如

HStack {文本域()文本(PLN")}.frame(对齐方式:.center)

但是 TextField 占用了所有可能的宽度.

我该如何处理,或者可能有其他解决方案.

解决方案

这是动态调整大小的 TextField 的可能方法.

注意:helper rectReader 取自

struct DemoCenterTextField:查看{@State 私有变量值 = ""@State 私有 var frame = CGRect.zerovar主体:一些视图{返回 HStack(对齐:.bottom){ZStack {文本(self.value).foregroundColor(Color.clear).fixedSize().background(rectReader($frame))TextField("#.#", 文本:$value).multilineTextAlignment(.trailing).frame(minWidth: 80, IdealWidth: frame.width).fixedSize(水平:真,垂直:假).border(Color.black)//<<仅用于演示}.font(Font.system(size: 40).bold())文本(PLN")}}}

I'm trying to implement such component

TextField (5 000) and Text (PLN) together should be centered horizontally. On entering new digit's, Text (PLN) should be dismissed. I think I have to combine this two views in to one container and center in, something like

HStack {
   TextField()
   Text("PLN")
}
.frame(alignment: .center)

But TextField is taking all possible width.

How could I handle it, or probably another solution.

解决方案

Here is possible approach with dynamically sized TextField.

Note: helper rectReader is taken from this my post.

Tested with Xcode 11.4 / iOS 13.4 (black border is only for demo)

struct DemoCenterTextField: View {
    @State private var value = ""
    @State private var frame = CGRect.zero

    var body: some View {
        return HStack(alignment: .bottom) {
            ZStack {
                Text(self.value).foregroundColor(Color.clear)
                    .fixedSize()
                    .background(rectReader($frame))

                TextField("#.#", text: $value)
                    .multilineTextAlignment(.trailing)
                    .frame(minWidth: 80, idealWidth: frame.width)
                    .fixedSize(horizontal: true, vertical: false)
                    .border(Color.black)      // << for demo only

            }.font(Font.system(size: 40).bold())

            Text("PLN")
        }
    }
}

这篇关于使 TextField 将其内容包装在 SwiftUI 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆