UIViewController里面的TableView

Nie*_*bæk 2 objective-c uitableview uiviewcontroller ios xcode4.2

我想在UIViewController中放一个tableView,因为我需要在视图顶部有一个工具栏,因此我不能使用tableViewController.我已经创建了一个tableView类,并将我认为所需的函数放入其中,但我必须丢失一些东西,或者在某处出错.

.H

import <UIKit/UIKit.h>

@interface TestTV : UITableView
@property(strong,nonatomic)NSArray *arr;

@end
Run Code Online (Sandbox Code Playgroud)

.M

#import "TestTV.h"

@implementation TestTV
@synthesize arr = _arr;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

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

    _arr = [[NSArray alloc]initWithObjects:@"HEJ",@"FOO", nil];
    return _arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:CellIdentifier];
    }

    NSString *cellValue = [_arr objectAtIndex:indexPath.row];
    cell.textLabel.text = cellValue;

    return cell;
}
@end
Run Code Online (Sandbox Code Playgroud)

war*_*enm 6

你可能不想要子类UITableView.相反,在视图控制器子类中,声明您打算实现适当的委托和数据源协议:

@interface MyViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
Run Code Online (Sandbox Code Playgroud)

然后,在视图控制器的实现文件中,实现上面定义的方法.

最后,在Interface Builder中(或以编程方式)将表视图的两个delegatedataSource出口设置为等于其superview的视图控制器(在IB中,此视图控制器是文件的所有者).

您也可以将数据数组作为视图控制器的属性.