我有以下功能,只要按下按钮就会运行:
func deletekeyPressed(sender: UIButton!) {
while(textDocumentProxy.hasText()) {
(textDocumentProxy as UIKeyInput).deleteBackward()
}
for _ in 1..<2000 {
(textDocumentProxy as UIKeyInput).deleteBackward()
}
}为了防止用户认为程序正在崩溃,我想要删除按钮的文本,它通常是"Delete All“到"Deleting...”或者更好的是让标题在以下状态之间交替:“正在删除”、“正在删除..”、“正在删除...”
到目前为止,我已经尝试在函数的开头和结尾放置UIControlState.Normal的setTitle(),以便在函数运行时使文本显示"Deleting“。
这使得我的函数看起来像这样:
func deletekeyPressed(sender: UIButton!) {
sender.setTitle("Deleting...", forState: .Normal)
while(textDocumentProxy.hasText()) {
(textDocumentProxy as UIKeyInput).deleteBackward()
}
for _ in 1..<2000 {
(textDocumentProxy as UIKeyInput).deleteBackward()
}
sender.setTitle("Deleting...", forState: .Normal)
}然而,什么都没有发生。如何实施此解决方案?
更新一:我像这样实现了Aaron的解决方案:
func deletekeyPressed(sender: UIButton!) {
NSLog("-------------------")
NSLog("Pressing delete key")
sender.setTitle("Deleting...", forState: .Normal)
sender.userInteractionEnabled = false
dispatch_async(dispatch_get_main_queue()) {
NSLog("Starting delete function")
while(self.textDocumentProxy.hasText()) {
NSLog("Deleting 3 times")
(self.textDocumentProxy as UIKeyInput).deleteBackward()
(self.textDocumentProxy as UIKeyInput).deleteBackward()
(self.textDocumentProxy as UIKeyInput).deleteBackward()
}
for _ in 1..<2000 {
(self.textDocumentProxy as UIKeyInput).deleteBackward()
}
sender.setTitle("Clear", forState: .Normal)
sender.userInteractionEnabled = true
NSLog("Finishing delete function")
}然而,我遇到了以下问题。该解决方案的部分作用在于,按钮文本将显示“正在删除...”直到dispatch_async内部的代码运行完毕。但问题是,文本字段的UI并没有在dispatch_async内部的代码完成运行后立即更新,其中的文本被删除。这会导致delete按钮的文本显示“正在删除...”短时间内(只要代码完成运行),即使UITextfield没有更新自身以显示代码的更改。
以下是该问题的视频:

注意delete函数是如何在屏幕更新之前完成调用的。
发布于 2016-06-22 11:17:48
问题是UI只有在主运行循环完成后才会绘制。因此,您更改文本的命令只有在工作完成后才会生效。
一个简单的解决方案是将删除工作安排在主队列的末尾:
func deletekeyPressed(sender: UIButton!) {
sender.setTitle("Deleting...", forState: .Normal)
sender.userInteractionEnabled = false
dispatch_async(dispatch_get_main_queue()) {
while(textDocumentProxy.hasText()) {
(textDocumentProxy as UIKeyInput).deleteBackward()
}
for _ in 1..<2000 {
(textDocumentProxy as UIKeyInput).deleteBackward()
}
sender.setTitle("Deleted!", forState: .Normal)
sender.userInteractionEnabled = true
}
}https://stackoverflow.com/questions/37957177
复制相似问题