将继承的子视图添加到我的视图中

时间:2011-01-20 14:00:51

标签: iphone objective-c ipad inheritance view


我目前正在开展一个具有很多相似性的项目。 我知道是否有办法将子视图从根类发送到继承的类。

这是我的RootViewController:

@class CustomView;
@interface RootViewController : UIViewController {
       IBOutlet CustomView  *_aCustomView;
}
@end

@implementation RootViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    UISwipeGestureRecognizer *swipRecognizer;

    // swipe left management
    swipRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self 
                                                               action:@selector(handleSwipeFrom:)];
    swipRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    swipRecognizer.numberOfTouchesRequired = 2;
    swipRecognizer.delegate = self;
    [self.view addGestureRecognizer:swipRecognizer];
    [swipRecognizer release];
}

- (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer
{
    NSLog(@"swip detected");
    [self.view addSubview:_aCustomView];
}

HomeViewController:

@interface HomeViewController : RootViewController {
}
@end

我会创建一些ViewController,它继承自RootViewController HomeViewController,以保存行代码。当我在HomeViewController时,我检测到我的滑动但我还没有设法将我的自定义subView(来自我的RootViewController)添加到我的HomeViewController。

很多。 问候,
kl94

2 个答案:

答案 0 :(得分:0)

您应该在自定义视图中添加构造函数方法,该方法使用模型中的对象初始化视图。

例如:

我的RootViewController是一个Customer对象,一个CustomerView显示有关该客户的信息。

在CustomerView中,您应该创建一个方法:

-(id) initWithFrame:(CGRect) frame customer:(Customer) customer;

如果您需要在HomeViewController中显示相同的CustomerView,只需添加一个Customer对象作为HomeViewController的属性,并在viewDidLoad中添加一个CustomerView:

CustomerView *customerView = [[CustomerView alloc] iniFrame:CGRectMake(...) customer:currentCustomer;
[self.view addSubView:customerView];
[customerView release];

希望这有帮助, 文森特。

答案 1 :(得分:0)

我找到了解决方案。我的问题是关于我试图添加一个未初始化的IBOutlet对象希望我以后不会后悔:

在我的HomeViewController中,我覆盖了方法initWithNibName:bundle:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
} 

我的RootViewController:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:@"RootViewController" bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}