SwiftUI - 封装一个字数限制 TextField 控件?
效果展示

代码
外部使用

封装控件代码

UI 相关
是否自动撑开?
这里使用 autoResize = false , 就是给定一个最大高度, 内部点击任何区域都弹出键盘。
autoResize = true, 意味着根据输入的内容自动撑开。 frame 的 height 设置为 0。

进度显示

非 UI
封装相关配置信息

键盘聚焦
要达到效果: 点击Textfield外围空白部分也能聚焦弹出键盘。

超出字符, 截断
当超过给定的限制字数, 输入直接截断
用到的修饰符.onChange(of: value, initial: true){ ... }

其他情况效果展示

实现效果: textField 只是 Zstack 布局上层的一个 view,随着输入字数换行自动设置高度。外部view没有限制高度, 点击也能让Textfield处于聚焦状态。
总结
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| # 进度圆环 Circle() .trim(from: 0, to: progress) .stroke(progressColor.gradient, lineWidth: 5) .rotationEffect(.degrees(-90)) # 空白区域点击TextField聚焦
声明: @FocusState private var isKeyboardShowing: Bool
.onTapGesture { isKeyboardShowing = true }
TextField(hint, text: $value, axis: .vertical) .focused($isKeyboardShowing)
# UI设置 .frame(height: config.autoResizes ? 0 : nil) 配置为自动撑开的话,textField底部视图隐藏。 只有TextField的情况, 随着输入字符换行自动撑高。 配置为不自动撑开, frame(height: nil)意味着,高度由父控件外部设置高度。不然就是和父级一样的高度。
|