gpt4 book ai didi

swift - UITextView 未触发委托(delegate)协议(protocol)函数

转载 作者:行者123 更新时间:2023-11-30 10:39:06 24 4
gpt4 key购买 nike

我有一个快速文件,我试图在其中创建一个自定义类来处理一页上多个 TextView 的占位符。我更喜欢一个单独的类,因为我认为处理多个 View 更干净。问题是,当这些事件发生时,函数 textViewDidEndEditingtextViewDidBeginEditing 不会被调用。

我已经通过将 PostPage 设置为委托(delegate)成功地工作了,但我不知道如何使用多个 UITextView 来做到这一点。

这是我的代码:

import UIKit

class PostPage: UIViewController, UITextViewDelegate {

@IBOutlet weak var eventDescription: UITextView!
@IBOutlet weak var eventTitle: UITextView!

var placeholderShowing = true

override func viewDidLoad() {
super.viewDidLoad()

// Add a placeholder for the text
let ph_descr = PlaceHolderHandler(placeholderText: "Description", textBox: eventDescription)
eventDescription.delegate = ph_descr

let ph_title = PlaceHolderHandler(placeholderText: "Title", textBox: eventTitle)
eventTitle.delegate = ph_title
}

}

class PlaceHolderHandler: NSObject, UITextViewDelegate {

var placeholderShowing = true
var placeholderText = ""

required init(placeholderText: String, textBox: UITextView) {
super.init()
self.placeholderText = placeholderText
textBox.text = placeholderText
textBox.textColor = UIColor.lightGray
}


// MARK:- UITextViewDelegates

public func textViewDidBeginEditing(_ textView: UITextView) {
if self.placeholderShowing {
textView.text = ""
textView.textColor = UIColor.black
self.placeholderShowing = false
}

}

public func textViewDidEndEditing(_ textView: UITextView) {
if textView.text == "" {
textView.text = "Description"
textView.textColor = UIColor.lightGray
self.placeholderShowing = true
}
}
}

当我选择任一 UITextView 时,我希望调用相应的函数,并相应地调整文本。

最佳答案

您需要保留 phDescrphTitle,因为在您的代码中它们是局部变量,因此在 viewDidLoad 结束时取消分配

>
import UIKit

class PostPage: UIViewController, UITextViewDelegate {

@IBOutlet weak var eventDescription: UITextView!
@IBOutlet weak var eventTitle: UITextView!

var placeholderShowing = true

var phDescr, phTitle:PlaceHolderHandler!

override func viewDidLoad() {
super.viewDidLoad()

// Add a placeholder for the text
phDescr = PlaceHolderHandler(placeholderText: "Description", textBox: eventDescription)
eventDescription.delegate = phDescr

phTitle = PlaceHolderHandler(placeholderText: "Title", textBox: eventTitle)
eventTitle.delegate = phTitle
}

}


也使用驼峰命名法来命名变量

I've had it successfully work by setting the PostPage to the delegate, but I don't see how I could do that with multiple UITextView

当然,您可以将两者的委托(delegate)设置为 PostPage 并了解哪一个是完整的使用

func textViewDidBeginEditing(_ textView: UITextView) {
if textView == eventDescription {
}
else { // eventTitle
}
}

关于swift - UITextView 未触发委托(delegate)协议(protocol)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57263424/

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