11

UIView 需要根据自定义控件的完成处理程序更改警告标签:

    voucherInputView.completionHandler = {[weak self] (success: Bool) -> Void in

        self?.proceedButton.enabled = success
        self?.warningLabel.alpha = 1.0

        if success
        {
            self?.warningLabel.text = "Code you entered is correct"
            self?.warningLabel.backgroundColor = UIColor.greenColor()
        }
        else
        {
            self?.warningLabel.text = "Code you entered is incorrect"
            self?.warningLabel.backgroundColor = UIColor.orangeColor()
        }


        UIView.animateWithDuration(NSTimeInterval(1.0), animations:{ ()-> Void in
            self?.warningLabel.alpha = 1.0
        })

最后的动画块在表单中显示错误。

Cannot invoke 'animateWithDuration' with an argument list of type '(NSTimeInterval), animations: ()-> Void)'

如果我在完成关闭之外的某个地方调用它,它就可以工作。

4

2 回答 2

39

问题是闭包隐式返回这个表达式的结果:

self?.warningLabel.alpha = 1.0

但是闭包本身被声明为返回Void

添加显式return应该可以解决问题:

UIView.animateWithDuration(NSTimeInterval(1.0), animations: { ()-> Void in
    self?.warningLabel.alpha = 1.0
    return
})
于 2014-09-24T16:49:37.053 回答
0

Antonio 的解决方案也适用于嵌套闭包,例如在 UITableViewRowAction 处理程序中执行 AFNetworking 请求。

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {

    let cleanRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Do Stuff", handler: {[weak self](action: UITableViewRowAction!, indexPath: NSIndexPath!) in

        AFHTTPSessionManager(baseURL: NSURL(string: "http://baseurl")).PUT("/api/", parameters: nil, success: { (task: NSURLSessionDataTask!, response: AnyObject!) -> Void in

                // Handle success

                self?.endEditing()
                return
            }, failure: { (task: NSURLSessionDataTask!, error: NSError!) -> Void in

                // Handle error

                self?.endEditing()
                return
        })
        return

    })

    cleanRowAction.backgroundColor = UIColor.greenColor()
    return [cleanRowAction]
}
于 2014-09-24T21:34:54.313 回答