【问题标题】:how to push view controller from a UIView's subclass如何从 UIView 的子类推送视图控制器
【发布时间】:2013-03-24 15:43:01
【问题描述】:

我从UIView 创建了一个视图“CategoryTableView”的子类。而CategoryTableView 包含一个UITableView。我将CategoryTableView 作为子视图添加到HomeViewController 来自UIViewController 的子类。现在,我想在didSelectRowAtIndexPath 执行时推送一个新的视图控制器。但是,在CategoryTableView 中,我如何推送或呈现另一个视图控制器。我无法访问CategoryTableView 中的导航控制器。

【问题讨论】:

  • 你没有。重新设计你的代码。
  • 完成。我正在使用委托,我现在可以推送到新的视图控制器。

标签: iphone objective-c uitableview uinavigationcontroller


【解决方案1】:

CategoryTableView.h

@property (retain, nonatomic) parentViewController *parent; //create one property for parent view like this

CategoryTableView.m

@sythesize parent;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [parent.navigationController . . .]; // preform action
    //OR..
    [parent presentModalViewController: . . .]; // present modal view
}

parent.m

//while calling your CategoryTableView assign self to your parent object

    CategoryTableView *tblView = [CategoryTableView alloc] init];
    tblView.parent = self;

【讨论】:

  • 如果 parentViewController 在 UINaviagationController 的堆栈中,那么它的有效代码。
  • 谢谢,它也有效。你的方法比我打算用委托方法好。
  • 老兄,你拯救了我的一天!
  • 这行得通,但这是不好的做法。 UIViews 不应该直接访问 navcon,因为它破坏了 MVC。破坏 MVC 并不意味着代码会失败,但它确实意味着您最终会得到意大利面条式代码,其中不清楚每个类的工作是什么,并且在大型项目中代码将变得难以辨认。 UIView 应该只是一个视图,呈现视觉效果但不控制任何应用程序逻辑。那是管制员的工作。这就是为什么你应该让你的 UIViewController 成为一个委托,它从你的 UIView 接收消息并执行导航逻辑本身。
【解决方案2】:

您需要使用自定义委托来实现此目的...

CategoryTableView.h

@protocol CategoryTableViewDelegate <NSObject>

-(void)pushViewControllerUsinDelegate:(UIViewController *)viewController;

@end

@interface CategoryTableView : UIView

@property (nonatomic, retain) id<CategoryTableViewDelegate> delegate;

@end

CategoryTableView.m

@implementation CategoryTableView

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Create the required UIViewControllers instance and call the delegate method.
    UIViewController *viewController = [[UIViewController alloc] init];
    [self.delegate pushViewControllerUsinDelegate:viewController];
}


@end

HomeViewController.h

 @interface HomeViewController : UIViewController <CategoryTableViewDelegate>

    @end

HomeViewController.m

@implementation HomeViewController

-(void)viewDidLoad
{
    [super viewDidLoad];

    //initialization of CategoryTableView like this...
    CategoryTableView *categoryTableViewInstance = [[CategoryTableView alloc] init];
    [categoryTableViewInstance setDelegate:self];

}

-(void)pushViewControllerUsinDelegate:(UIViewController *)viewController
{
    [self.navigationController pushViewController:viewController animated:YES];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多