如何使多个视图控制器的表视图通用

时间:2014-07-30 06:07:00

标签: ios uitableview

我正在尝试使用公共表视图创建多个视图控制器,但我无法做到这一点我已经创建了一个视图文件并添加了表视图并将该文件导入到所有视图控制器但是无法获得相同的表查看每个

这是代码:

//
//  LeftTableViewClass.h
// 
//
//  Created by   on 30/07/14.
//  Copyright (c) 2014   All rights reserved.
//

#import <UIKit/UIKit.h>

@interface LeftTableViewClass : UITableView <UITableViewDataSource,UITableViewDelegate>

@end

//
//  LeftTableViewClass.m
// 
//
//  Created by  on 30/07/14.
//  Copyright (c) 2014   All rights reserved.
//

#import "LeftTableViewClass.h"

@implementation LeftTableViewClass

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 4;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    //cell.contentView.layer.borderWidth = 1.0f;
    //cell.contentView.layer.cornerRadius = 4.0f;

    cell.textLabel.text = @"test";


    return cell;

}

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSLog(@"%d",indexPath.row);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

LeftTableViewClass *leftTableViewClass = [[LeftTableViewClass alloc] init];
[self.view addSubview:leftTableViewClass];

3 个答案:

答案 0 :(得分:0)

您可以创建一个表视图类并初始化(alloc)它一次并保留所有控制器的引用。

答案 1 :(得分:0)

我认为你在这里犯的错误是你认为你需要继承UITableView来定义它的行为。但是Apple在这里使用了委托设计模式。任何UITableView都有两个我们应该担心的属性。 delegatedataSource

委托模式是指对象将某些操作委托给其他对象。在这种情况下,您可以将UITableView的delegatedatasource属性设置为定义其行为的对象。 delegate告诉表格查看采取行动时要做什么(如选择单元格)。 dataSource用于表示有多少单元格以及有多少单元格。

在您的情况下,您可以进行子类化(虽然这不是必需的)但您从未为表格视图设置dataSourcedelegate。如果愿意,可以在init方法中执行此操作。

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.dataSource = self;
        self.delegate = self;
    }
    return self;
}

现在告诉表视图将自己用作委托和dataSource。有关UITableView here的更多信息,请参阅此文章。

答案 2 :(得分:0)

使用costructor方法创建一个UIView子类,该方法收集 数据源数据[array]和帧值 ,然后在类中包含表的代码参考视图的帧大小,并通过创建实例并添加为子视图,随时显示它。

为什么您当前的选项不起作用

未提供您创建的LeftTableViewClass实例的框架。 框架是添加子视图的关键。使用initWithFrame方法

进行实例分配

使用

LeftTableViewClass *leftTableViewClass = [[LeftTableViewClass alloc] initWithFrame:CGRectMake(0, 0, 150, 200)];
相关问题