標籤:swift ios
接著上一篇的Blog講,在我們自訂了TableViewCell之後,我們可能需要點擊cell裡面的button等操作,比如點擊了以後跳轉到別的頁面,這個時候,因為跳轉動作是在tableview所在的viewcontroller(假設為A類)實現的,所以,我們需要在tablewViewCell類裡面調用A類的一個執行個體,這個執行個體一般是通過AppDelegate類實現的。
具體來看一下實現過程。
我們先來看一下整體的需求:
在“基站列表”這個ViewController裡面,我們的TableViewCell是自訂的,然後在我們自訂的cell裡面,有按鈕,我們點擊按鈕以後,跳轉到下一個介面,Segue的identifier是“showInfoForStation”。
很明顯,我們的需求是:在cell的類中button的action裡面,擷取到“基站列表”ViewContrller的一個執行個體,這個執行個體有個方法,可以實現介面的跳轉。
好了,上代碼:
AppDelegate.Swift
import UIKit@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var projectDetail = ProjectDetailViewController() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let mainSB = UIStoryboard(name: "Main", bundle: nil) self.projectDetail = mainSB.instantiateViewControllerWithIdentifier("projectDetailVC") as! ProjectDetailViewController return true }
首先聲明我們想要的viewController的執行個體,這裡我命名為projectDetail
這裡在didFinishLaunchingWithOptions函數裡面其實得到的是空,因為ViewController只有在它被調用的時候,才被執行個體化,也就是viewDidLoad只有在首次調用該介面的時候,才會執行個體化改類。
所以接下來我們需要在ProjectDetailViewControler類的ViewDidLoad函數中真正把這個viewcontroller的執行個體賦予AppDelegate
ProjectDetailViewController.swfit
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate appdelegate.projectDetail = self self.tableView.delegate = self self.tableView.dataSource = self // remove the blank of the header of the table view, mind the height must be more than 0 self.tableView.tableHeaderView = UIView(frame: CGRectMake(0, 0, self.tableView.frame.size.width, 0.01)) // register the custom tableview cell var nib = UINib(nibName: "StationTableViewCell", bundle: nil) self.tableView.registerNib(nib, forCellReuseIdentifier: "cell") }
這裡的代碼和上一篇blog的代碼一樣,就不多介紹,關鍵性的代碼就是那兩行:
let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate appdelegate.projectDetail = self
同時實現一個
methode,用於別的類裡面調用改方法可以實現頁面的跳轉:
// Methord to show the other VC For the AppDelegate to call func showStationDetail()->(){ self.performSegueWithIdentifier("showInfoForStation", sender: self) }這裡的跳轉動作和之前在storyBoard裡面的segue的indentifier一樣,是showInfoForStation
最後,在自訂的cell裡面完成button的點擊action函數就ok了
StationTableViewCell.swift
@IBAction func buttonPressed(sender: AnyObject) { let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate appdelegate.projectDetail.showStationDetail() }
Swift中利用AppDelegate實現調用指定ViewController中的函數