gpt4 book ai didi

swift - UITextView 的占位符文本与 First Responder 混合

转载 作者:搜寻专家 更新时间:2023-10-31 22:17:54 26 4
gpt4 key购买 nike

我目前有一个带有占位符文本的 TextView ,每当用户点击 TextView 时,该 TextView 就会消失,并且如果 TextView 为空,则每当第一响应者辞职时, TextView 中的文本就会重新出现。 (这是我使用的代码,以防有人想使用它)

*注意,先将textview的文字颜色设置为浅灰色,并设置占位符文字。然后使用这些方法:

func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
//If it begins editing, then set the color to black
if (textView.tag == 0){
textView.text = ""
textView.textColor = .black
textView.tag = 1
}
return true
}


func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Example: I started my career as a street wear model based in Maryland. After 3 years of working with some of the top companies there, I moved to LA, where I currently reside. I’ve been featured in shows, 12 magazines, commercials, and a number of music videos. Now, Im currently looking to continue working with clothing companies and campaigns."
textView.textColor = .lightGray
textView.tag = 0
}
}

我想更上一层楼。现在,只要 TextView 成为第一响应者,文本就会消失。 我希望文本在用户实际开始输入时消失,而不仅仅是在选择 TextView 时消失。当屏幕出现时,我自动将第一响应者设置为 TextView 并计划保留它那样。但是因为它是自动设置的,所以您看不到占位符文本。 我只希望 TextView 在用户按下某个键时消失,而不是因为它被选中。

最佳答案

假设您有这样的占位符文本,

let placeholderText = "Example: I started my career as a street wear model based in Maryland. After 3 years of working with some of the top companies there, I moved to LA, where I currently reside. I’ve been featured in shows, 12 magazines, commercials, and a number of music videos. Now, Im currently looking to continue working with clothing companies and campaigns."

并且在调用 becomeFirstResponder 之前,您在 storyboardviewDidLoad 中将此文本设置为 textView > TextView

然后在这两个委托(delegate)方法中,您可以实现如下行为,

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if textView.text == placeholderText {
textView.text = ""
}
return true
}

func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = placeholderText
}
}

目前您正在清除 textViewShouldBeginEditing 中的文本,因此,这是您看不到该文本的主要原因。您应该删除清除那里的文本,但您可以按原样继续更改颜色等。

关于swift - UITextView 的占位符文本与 First Responder 混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51054103/

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