gpt4 book ai didi

swift - TextView 将前两个字符大写而不是一个

转载 作者:行者123 更新时间:2023-11-30 10:33:28 26 4
gpt4 key购买 nike

因此,我向 UITextView 添加了占位符功能,现在它会将输入文本的前两个字符大写,而不是像预期的那样大写一个。

如果你们能以任何方式提供帮助,我将非常感谢你们帮助解决这个问题。我一直在努力,但似乎一事无成。

代码如下:

class ViewController: UIViewController {

@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
super.viewDidLoad()

textView.delegate = self
textView.text = "Type something"
textView.textColor = UIColor.rgb(197, 197, 199)
}

}

extension ViewController: UITextViewDelegate {

// Put cursor at the beginning of TextView when editing begins
func textViewDidBeginEditing(_ textView: UITextView) {
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
}

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// Sets placeholder for UITextView
let updatedText = (textView.text as NSString).replacingCharacters(in: range, with: text)
if updatedText.isEmpty {
textView.text = "Type something"
textView.textColor = UIColor.rgb(197, 197, 199)
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
} else if textView.textColor == UIColor.rgb(197, 197, 199) && !text.isEmpty {
textView.textColor = UIColor.black
textView.text = text
} else {
return true
}

return false
}

// Prevents selecting the placeholder
func textViewDidChangeSelection(_ textView: UITextView) {
if self.view.window != nil {
if textView.textColor == UIColor.rgb(197, 197, 199) {
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
}
}
}

}

谢谢!

最佳答案

下面的代码解决了 TextView 中前两个字母的大写问题。

func textViewDidChange(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Type something"
textView.textColor = self.placeholderTextColor
} else {
textView.textColor = .black
}
}

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text.isEmpty {
let updatedText = (textView.text as NSString).replacingCharacters(in: range, with: text)
if updatedText.isEmpty {
textView.text = "Type something"
textView.textColor = self.placeholderTextColor
textView.selectedRange = NSRange(location: 0, length: 0)
}
} else {
if textView.text == "Type something" {
textView.text = ""
}
textView.textColor = .black
}
return true
}

TextView 中前 2 个字符大写的原因是您在下面的委托(delegate)方法中返回了 false

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool

关于swift - TextView 将前两个字符大写而不是一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58583806/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com