簡體   English   中英

在TableView的CustomCell中獲取UIViewController

[英]Get the UIViewController in TableView's CustomCell

我有一個名為“ MainView”的UIViewController ,並且有一個名為“ tblLists”的UITableView
tblLists生成customCell “ customCellList”。

我的問題是可以在customCellList類中獲取MainView的實例(自己)。

我嘗試用superview的東西,但沒有得到MainView 我想在沒有協議的情況下實現這一目標。

因此需要您的幫助。

您可以使用響應者鏈來訪問視圖控制器。 假設您的customCell類是UITableViewCell子類,則應使用以下方法完成此工作:

@implementation customCell

- (UIViewController *)getViewController
{
   id vc = [self nextResponder];
   while(![vc isKindOfClass:[UIViewController class]] && vc!=nil)
   {
       vc = [vc nextResponder];
   }

   return vc;
}

@end

上面的代碼由Sensible TableView框架提供。

您要問的不是一個好主意,您應該找到另一種解決方法。 它破壞了MCV模式。 順便說一句,如果您擔心使用ARC和將iOS> = 5作為目標的內存問題,則可以創建對表視圖本身的弱引用,並獲得視圖控制器作為其委托或數據源屬性(當然,如果VC是一個他們)。 或者,您可以創建對VC本身的弱引用。
正如評論中指出的那樣,這不是一個好主意,最好找到另一種解決方法。 如果您需要更新單元格值,則有很多方法可以重新加載tableview數據! 通過在模型中的VC上使用KVO,通知,委派等,您可以簡單地觸發重新加載到表視圖,而無需在單元格中包含奇怪的引用。
希望這可以幫助。

對於那些想中斷MVC的罕見情況。.這假定您使用導航控制器作為窗口上的rootVC。 為Swift 2更新

func visibleVC() -> UIViewController? {
        if let navVC: UINavigationController = UIApplication.sharedApplication().keyWindow?.rootViewController as? UINavigationController {
            if let vc: UIViewController = navVC.visibleViewController as? MyViewControllerClass {
                return vc
            }
        }
        return nil
    }

您還可以訪問rootViewController:

UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;

我有類似的問題,我的情況是在Table View自定義單元格中的textfield值更改時,在View Controller中更改數組。

我的解決方案是在tableview cellForRowAt方法中為UITextFiled添加委托,然后可以在textFieldDidEndEditing方法中更改所有數據。 因為它們全部在一個類中,所以它是ViewController類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM