如何在功能运行时更改按钮文本

时间:2016-06-22 01:38:53

标签: ios

每当按下按钮时,我都会运行以下功能:

func deletekeyPressed(sender: UIButton!) {

    while(textDocumentProxy.hasText()) {
        (textDocumentProxy as UIKeyInput).deleteBackward()
    }

    for _ in 1..<2000 {
        (textDocumentProxy as UIKeyInput).deleteBackward()
    }

}

为了防止用户认为程序崩溃我希望删除按钮的文本通常显示为&#34;全部删除&#34;到&#34;删除...&#34;甚至更好地使标题在以下状态之间交替:&#34;删除&#34;,&#34;删除。&#34;,&#34;删除...&#34;,&#34;删除。 ..&#34;

到目前为止,我已尝试在函数的开头和结尾添加setTitle() UIControlState.Normal,以使文本说“&#34;删除&#34;当函数运行时。

这使我的功能看起来像这样:

    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")
    }

但是我遇到了以下问题。该解决方案部分工作在按钮文本将说&#34;删除...&#34;直到dispatch_async内的代码完成运行。但问题是,只要dispatch_async内的代码完成运行,就不会更新正在删除文本的文本域UI。这导致删除按钮的文字说“&#34;删除...&#34;即使UITextfield没有自我更新以显示代码的变化,也会花费很短的时间(只要代码完成运行)。

以下是该问题的视频:

bugdemo

注意删除功能在屏幕更新之前如何完成调用方式。

1 个答案:

答案 0 :(得分:2)

问题是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
    }
}