【问题标题】:TableView inside UIViewControllerUIViewController里面的TableView
【发布时间】:2012-03-18 22:51:19
【问题描述】:

我想在 UIViewController 中放置一个 tableView,因为我需要在视图顶部有一个工具栏,因此我不能使用 tableViewController。我创建了一个 tableView 类,并将我认为需要的功能放入其中,但我一定遗漏了一些东西,或者在某处放了一些错误。

.h

import <UIKit/UIKit.h>

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

@end

.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

【问题讨论】:

    标签: objective-c ios uitableview uiviewcontroller xcode4.2


    【解决方案1】:

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

    @interface MyViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
    

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

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

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

    【讨论】:

    • 现在我无法从 tableView 中的单元格或工具栏中的任何按钮中分离
    • 如果您在谈论 Storyboard segues,我对它们并不熟悉。另一方面,您当然可以使用IBActions 和tableView:didSelectRowAtIndexPath: 委托方法来实现您想要的任何东西。
    • 有机会获得此答案的更新版本吗?我正在尝试,但得到一个错误,你不能专门化非泛型类型 UIViewController...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 2017-01-04
    相关资源
    最近更新 更多