2017-08-07 35 views
0

我有一個tableViewCell,它爲tableview中的每個單元格保存一些函數。我希望這些功能之一向視圖呈現activityIndicator,以防止用戶與應用程序交互,直到完成該功能。通常,這可以通過使用來完成:如何使用tableViewCell將視圖添加到viewController?

var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView() 
func exampleFunc(){ 
     activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0,y: 0,width: 50,height: 50)) 
     activityIndicator.center = self.view.center //can't be used as self.view doesn't exist because self is a tableviewCell 
     activityIndicator.hidesWhenStopped = true 
     activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray 
     view.addSubview(activityIndicator) //also can't be used 
     activityIndicator.startAnimating() 
     UIApplication.shared.beginIgnoringInteractionEvents() 
     if x<y{ 
      self.activityIndicator.stopAnimating() 
      UIApplication.shared.endIgnoringInteractionEvents() 
     } 

    } 

這樣做的問題是,因爲該功能被容納在tableViewCell因此self被參照tableViewCell等等self.view是不可用的self.view.center不能使用。我如何將這個活動指標添加到tableViewCell中,儘管它在tableViewCell

+1

爲什麼把代碼中的單元格顯示活動的指標,而不是在表視圖本身? – NRitH

+0

您可以使用通知或委託,同時將活動指示符保留在viewController中,併發布來自tableViewCell –

+0

@NRitH的通知,因爲每個單元格中所有按鈕的功能都保存在單元格中...並且這些按鈕是我想用顯示活動指示器 –

回答

1

創建一個協議,如:

protocol MyTableViewCellDelegate { 
    func showActivityIndicator() 
} 

然後在你的UITableViewCell創建一個MyTableViewCellDelegate參考:

var delegate: MyTableViewCellDelegate? 

然後讓你的控制器符合新的協議,例如:

class MyViewController: UIViewController, MyTableViewCellDelegate { 

... 

    func showActivityIndicator() { 
     // implement your ActivityIndicator logic here 
    } 
} 

將您的單元的委託設置爲您的控制器。然後,每當你的需要顯示的ActivityIndi​​cator所有你需要調用是:

delegate?.showActivityIndicator() 
相關問題