swiftui - SwiftUI TextEditor #hashtags 和文本占位符正确支持
问题描述
我要添加的内容:
- TextEditor中对占位符文本的支持几乎是完美的,除了当我开始在字段中点击时,占位符和类型光标未对齐,所以我想实现与标准TextField对占位符所做的非常相似的行为。
- 使用背景颜色和角半径检测并突出显示TextEditor内的#hashtags。我有一个功能来检测 #hashtags 并放置在名为 textWithHashtags 的单独视图中,但我想知道是否有可能进行一些转换并使其对TextEditor有用?
如果您有解决方案,请告诉我,非常感谢。这是代码:
struct ContentView: View {
@Environment(\.presentationMode) var presentationMode
@State private var messageToSend = ""
var body: some View {
NavigationView {
GeometryReader { geometry in
ZStack {
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: geometry.size.height * 0.1) {
ZStack(alignment: .leading) {
if messageToSend.isEmpty {
Text("Type message here")
.foregroundColor(.gray.opacity(0.7))
.padding([.leading], 8)
.zIndex(1)
}
TextEditor(text: $messageToSend)
.frame(height: geometry.size.height * 0.20)
.keyboardType(.alphabet)
.font(.system(size: 18))
.foregroundColor(Color.primary.opacity(0.8))
.padding(8)
}
.background(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.stroke(Color.black, lineWidth: 1)
)
Button {
// action
} label: {
Image(systemName: "paperplane")
.font(.system(size: 20))
.foregroundColor(.white)
.padding()
.frame(width: geometry.size.width * 0.2, height: 45)
.background(
RoundedRectangle(cornerRadius: 8, style: .continuous)
.fill(Color.blue.opacity(1))
)
}
}
.frame(width: geometry.size.width * 0.7, height: geometry.size.height, alignment: .center)
}
.frame(
minWidth: 0,
idealWidth: geometry.size.width * 0.8,
maxWidth: .infinity,
minHeight: 0,
idealHeight: geometry.size.height,
maxHeight: .infinity,
alignment: .center
)
}
.navigationBarItems(leading: Button("Cancel", action: { presentationMode.wrappedValue.dismiss() }))
.navigationBarTitle(Text(""))
}
}
}
func textWithHashtags(_ text: String, color: Color) -> Text {
let words = text.split(separator: " ")
var output: Text = Text("")
for word in words {
if word.hasPrefix("#") { // Pick out hash in words
output = output + Text(" ") + Text(String(word))
.foregroundColor(.blue)
} else {
output = output + Text(" ") + Text(String(word))
}
}
return output
}
}
解决方案
推荐阅读
- git - 不明白为什么 git merge -s ours 会忽略以前的提交
- javascript - 将每个其他数组元素的第一个字母大写
- flutter - 值更改后小部件宽度不更新
- android - 如何调整每个平台的小部件大小?
- javascript - React - 如何将两个值而不是一个传递给钩子
- flutter - 增加从顶部到网格视图第一行的内边距
- python - 从 sympy 获得不定积分
- java - 在应用程序中的时间过去后显示文本
- for-loop - 在 Go 中循环切片以创建地图
- java - 在 RESTful Spring Boot 应用程序中,如何对嵌套对象属性进行 url 查询?