满足条件后如何在swift中停止活动指示器?
我已经在我的模型的扩展中声明了一个UIActivityIndicatorView作为计算属性。 我有一个方法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 } } }
您将activityIN
定义为计算变量。 无论何时调用它,都会得到全新的实例。 在UIActivityIndicatorView
便利初始化器中查看activityIN
var。 如果您只需要十秒钟的活动,请像这样编辑您的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 } } }
但通常您需要继续引用从此初始化程序获得的实例。 在TransactionCell
类中定义UIActivityIndicatorView
存储属性。
假设TransactionCell
类有声明
var cellActivityIndicator: UIActivityIndicatorView!
那么你可以像这样编辑你的function
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 } } }