ios - 如何在一个 View Controller 中快速将占位符设置为多个 TextView

标签 ios swift uitextview placeholder

我有一个 View Controller ,其中包含两个 TextView (storyTitle 和storyDe​​scription)。我已向两个 TextView 添加了占位符,下面的代码将向您展示我是如何做到这一点的:

// Setup the story title text field
func setupStoryTitleTextView() {

    storyTitle.textColor = .gray
    storyTitle.text = "Add story title"
    storyTitle.textContainerInset = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
    self.storyTitle.delegate = self

    view.addSubview(storyTitle)

}
// Setup the storyDescription text view
func setupStoryDescriptionTextView() {

    storyDescription.text = "Description of the story"
    storyDescription.textColor = .gray
    storyDescription.textContainerInset = UIEdgeInsets(top: 10, left: 20, bottom: 300, right: 20)
    self.storyDescription.delegate = self

    view.addSubview(storyDescription)

}
// To remove placeholder text when the user starts typing
func textViewDidBeginEditing(_ textView: UITextView) {

    // Story title text view
    if storyTitle.textColor == .gray {
        storyTitle.text = nil
        storyTitle.textColor = .black
    }

    // Story description text view
    if storyDescription.textColor == .gray {
        storyDescription.text = nil
        storyDescription.textColor = .black
    }
}
// To bring the placeholder back when the text views don't contain any text
func textViewDidEndEditing(_ textView: UITextView) {

    // Story title text view
    if storyTitle.text.isEmpty {
        storyTitle.text = "Add story title"
        storyTitle.textColor = .gray
    }

    // Story description text view
    if storyDescription.text.isEmpty {
        storyDescription.text = "Description of the story"
        storyDescription.textColor = .gray
    }
}

这里发生的情况是,当我点击一个 TextView 时,两个 TextView 中的占位符都会消失,这是因为 textViewDidBeginEditing 下的两个 if 条件都被执行了。我怎样才能防止这种情况发生?感谢任何形式的帮助,谢谢:)

最佳答案

您可以通过为 View 对象(您的 TextView )分配标签来轻松完成此操作。使用 textview.tag = [某个数字] 分配标签,然后您还可以向条件中添加类似的内容:

storyDescription.tag = 1

func textViewDidBeginEditing(_ textView: UITextView) {
    if textView.tag == 1 && storyTitle.textColor == .gray {
        storyTitle.text = nil
        storyTitle.textColor = .black
    }
}

这与其他 TextView 类似

关于ios - 如何在一个 View Controller 中快速将占位符设置为多个 TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56940430/

相关文章:

ios - 在当前 View Controller 下呈现新的 View Controller

xcode - 使用 Swift 在 tableView 中重新排序 Realm.io 数据

ios - ResourceManager.write Data(for...不会在 iOS 14 上运行

iOS UITextView 不会调整大小

html - IOS 在 HTML 中导致不需要的换行符

ios - 每日通知 Swift 3

ios - 如何设置具有间隔/延迟的循环?

ios - 从 View 更改 View 将出现

iphone - ScrollView ios 中的 TextView

swift - 为什么 resignFirstResponder 在 UITextView 上重置 contentOffset?