2016-06-22 36 views
0

更改按鈕的文本我有一個運行時按下按鈕以下功能:如何在以功能正在運行

func deletekeyPressed(sender: UIButton!) { 

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

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

} 

爲了防止用戶從思維程序崩潰我想刪除按鈕的文字通常說「全部刪除」爲「正在刪除...」,或者甚至更好地在下列狀態之間交替標題:「刪除」,「刪除」,「刪除...」,「刪除...」

到目前爲止,我已經嘗試在函數的開始和結尾處放置的setTitle()以使文本在「刪除」時顯示該功能正在運行。

這使我的功能看起來像這樣:

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

然而,什麼也沒有發生。我如何實施這個解決方案?

更新一:我實現了亞倫的解決方案是這樣的:

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內的代碼完成運行。但問題在於dispatch_async內的代碼完成運行後,文本將被刪除的文本字段的UI不會更新。這會導致刪除按鈕的文本在短時間內顯示「正在刪除...」(只要代碼完成運行所需的時間),即使UITextfield未更新自身以顯示代碼更改。

這是問題的一個視頻:

bugdemo

通知刪除功能如何完成屏幕更新之前調用方式。

回答

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 
    } 
} 
+0

快速的問題,你是什麼意思「的主要運行循環完成」?這是指在函數中執行的任何內容,因此表示直到函數完成調用後UI纔會更新? – Roymunson

+0

也有一些奇怪的事情正在發生。該解決方案的部分原理是,按鈕顯示文本「正在刪除...」,直到「dispatch_async」中的代碼完成運行,但由於某種原因,只要dispatch_async中的代碼不會將該文本顯示爲被刪除完成運行,而是有明顯的停頓。結果是按鈕說「已刪除!」在文本被實際刪除之前。我會在一秒鐘後發佈這個視頻。 – Roymunson

相關問題