gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:40:27 26 4
gpt4 key购买 nike

我有一个 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 = [some number] 分配一个标签,然后您还可以在您的条件中添加类似这样的内容:

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/

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