满足条件后如何在swift中停止活动指示器?

问题描述 投票:1回答:1

我已经在我的模型的扩展中声明了一个UIActivityIndi​​catorView作为计算属性。我有一个方法configureCell,我正在尝试使用活动指示器作为imageView的子视图。在这里,我能够将指标置于特定条件下,但以后无法对其进行任何更改。例如,我无法停止活动指示器,无法更改颜色,甚至无法隐藏它。

extension TranscationModel: UITableViewDataSource, UITableViewDelegate
{

 var activityIN: UIActivityIndicatorView {
    var act = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    act.color = UIColor.redColor()
    act.hidden = false
    act.startAnimating()
    return act
}

func configureTransactionCell(cell : TransactionCell?, indexPath: NSIndexPath) {
    if transaction.tid == "Something" {
        activityIN.color = UIColor.greenColor() //Even this doesn't work
        activityIN.center = cell.imgTransactionBill.center
        cell.imgTransactionBill.addSubview(activityIN)
        let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(10 * Double(NSEC_PER_SEC)))
        dispatch_after(delayTime, dispatch_get_main_queue()) {
             activityIN.stopAnimating() //Not working
             activityIN.hidden = true   //Not working
        }
    }
}
ios swift uiactivityindicatorview tableviewcell
1个回答
6
投票

您将activityIN定义为计算变量。每次调用它时,都会得到全新的实例。看看activityIN var就像UIActivityIndicatorView的便利初始化一样。如果您只需要十秒钟的活动,请按以下方式编辑您的func:

func configureTransactionCell(cell : TransactionCell?, indexPath: NSIndexPath) {
    if transaction.tid == "Something" {
        let weakActivityIndicator = activityIN
        weakActivityIndicator.color = UIColor.greenColor()
        weakActivityIndicator.center = cell.imgTransactionBill.center
        cell.imgTransactionBill.addSubview(weakActivityIndicator)
        let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(10 * Double(NSEC_PER_SEC)))
        dispatch_after(delayTime, dispatch_get_main_queue()) {
             weakActivityIndicator.stopAnimating()
             weakActivityIndicator.hidden = true
        }
    }
}

但通常您需要保留对此初始值设定项的实例的引用。在UIActivityIndicatorView类中定义TransactionCell存储属性。

假设TransactionCell类有声明

var cellActivityIndicator: UIActivityIndicatorView!

那么你可以像这样编辑你的功能

func configureTransactionCell(cell : TransactionCell?, indexPath: NSIndexPath) {
    if transaction.tid == "Something" {
        cell.cellActivityIndicator = activityIN
        cell.cellActivityIndicator.color = UIColor.greenColor()
        cell.cellActivityIndicator.center = cell.imgTransactionBill.center
        cell.imgTransactionBill.addSubview(cell.cellActivityIndicator)
        let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(10 * Double(NSEC_PER_SEC)))
        dispatch_after(delayTime, dispatch_get_main_queue()) {
             cell.cellActivityIndicator.stopAnimating()
             cell.cellActivityIndicator.hidden = true
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.