我目前有一个带有占位符文本的文本视图,每当用户点击文本视图时,占位符文本就会消失,并且如果文本视图为空,则每当第一响应者辞职时,文本视图中的文本就会重新出现。(这是我使用的代码,以防有人想使用它)
\n\n*注意,首先将textview的文本颜色设置为浅灰色,并设置占位符文本。然后使用这些方法:
\n\nfunc textViewShouldBeginEditing(_ textView: UITextView) -> Bool {\n //If it begins editing, then set the color to black\n if (textView.tag == 0){\n textView.text = ""\n textView.textColor = .black\n textView.tag = 1\n }\n return true\n}\n\n\nfunc textViewDidEndEditing(_ textView: UITextView) {\n if textView.text.isEmpty {\n 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\xe2\x80\x99ve 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."\n textView.textColor = .lightGray\n textView.tag = 0\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我想把事情更上一层楼。现在,只要文本视图成为第一响应者,文本就会消失。我希望每当用户实际开始输入时文本就会消失,而不仅仅是在选择文本视图时消失。当屏幕出现时,我自动将第一响应者设置为文本视图,并且我计划保持这种状态。但由于它是自动设置的,因此您无法看到占位符文本。我只希望每当用户按下某个键时文本视图就会消失,而不是因为它被选中。
\n假设您有一个占位符文本,如下所示,
\n\nlet 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\xe2\x80\x99ve 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."\nRun Code Online (Sandbox Code Playgroud)\n\n并且您在调用之前将此文本设置为textViewinstoryboard或 in 。viewDidLoadbecomeFirstRespondertextView
然后在这两个委托方法中您可以实现此行为,如下所示,
\n\nfunc textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {\n if textView.text == placeholderText {\n textView.text = ""\n }\n return true\n}\n\nfunc textViewDidEndEditing(_ textView: UITextView) {\n if textView.text.isEmpty {\n textView.text = placeholderText\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n目前您正在清除so中的文本textViewShouldBeginEditing,这是您看不到该文本的主要原因。您应该删除清除那里的文本,但您可以继续更改颜色等。
| 归档时间: |
|
| 查看次数: |
7307 次 |
| 最近记录: |