gpt4 book ai didi

swift - textViewDidChange 函数没有响应

转载 作者:行者123 更新时间:2023-11-28 14:25:35 25 4
gpt4 key购买 nike

我正在尝试编写 Swift 代码以在每次用户键入任何文本时更改我的 UITextView 中的背景颜色。我已经委托(delegate)了我的 UITextView 并添加了 textViewDidChange:

extension DocumentViewController: UITextViewDelegate {

func textViewDidChange(_ textView: UITextView) {
let currentText = self.textView.text

var seed = 0

if currentText != self.textView.text {
let myNum = seed%4
let myColor = colorPicker(num: myNum)
self.textView.backgroundColor = myColor
seed += 1
}
}

func colorPicker(num: Int) -> UIColor {
let colors = [UIColor.red, UIColor.blue, UIColor.green, UIColor.purple]

return colors[Int(num)]
}

}

这段代码对我来说似乎是合乎逻辑的,Xcode 没有给我任何错误,但是,当我运行程序时,我没有得到想要的结果。

为了进一步测试我的功能,我尝试打印我的变量 seed 并且值递增 1。但是,值保持在 1,并且不会像我想的那样在每次键入时继续递增会,我的输出如下所示:

1
1
1
1
1
1
1

我还尝试在我的 DocumentViewController 类中添加 var seed = 0 并将我的调用更改为 self.seedtextViewDidChange 这样:

func textViewDidChange(_ textView: UITextView) {

let currentText = self.textView.text
if currentText != self.textView.text {

let myNum = self.seed % 4
let myColor = colorPicker(num: myNum)
self.textView.backgroundColor = myColor
self.seed += 1
}
}

但是种子不会更新甚至打印。

总而言之,我的 textViewDidChange 没有响应任何进一步的更改。关于这个问题可能是什么的任何想法?

最佳答案

控件永远不会进入if as

if currentText != self.textView.text 

等于

if self.textView.text != self.textView.text 

这是错误的

//

在类 DocumentViewController 中将 seed 声明为实例变量

var seed = 0
var oldText = ""

//

func textViewDidChange(_ textView: UITextView) { 

if oldText != self.textView.text! {

let myNum = seed%4
let myColor = colorPicker(num: myNum)
self.textView.backgroundColor = myColor
seed += 1
oldText = self.textView.text!
}
}

//

还有一件事要提,如果用户编辑它,则不需要 oldText var,因为文本将始终保留新的更改,如果您从不知道内容的服务器调用中设置它,则保留它

关于swift - textViewDidChange 函数没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51615107/

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