无法在Iphone中识别TableView的子视图

时间:2013-11-11 10:29:32

标签: ios iphone objective-c uitableview tags

我添加了一个带按钮的标题视图&一个imageview但我无法识别Imageview以更改图像。

我的代码如下:

我的HaderView类.h文件(HeaderSection.h)

#import <UIKit/UIKit.h>

@interface HeaderViewSection : UIView
@property(nonatomic,retain)UIButton *btn;
@property(nonatomic,retain)UIImageView *arrow_img;
@end

我的HaderView类.m文件(HeaderSection.m)

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor brownColor];

        _arrow_img=[[UIImageView alloc]init];
        _arrow_img.frame=CGRectMake(280, 15, 20, 20);
        _arrow_img.image=[UIImage imageNamed:@"Arrow_down_section.png"];
        _arrow_img.backgroundColor=[UIColor clearColor];
        [self addSubview:_arrow_img];

        btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(20, 15, 35, 25);
        [btn setTitle:@"R" forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor blackColor];
        [self addSubview:btn];

    }

    return self;
}

.h文件

#import "HeaderViewSection.h"
@property (nonatomic,retain)HeaderViewSection *header_view;

.m文件

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    _header_view = [[HeaderViewSection alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    _header_view.tag = section+5000;
    _header_view.btn.tag = section+5000;
    [_header_view.btn addTarget:self action:@selector(expandTableHeaderView:) forControlEvents:UIControlEventTouchUpInside];
    _header_view.arrow_img.tag=section+2000;

    return _header_view;

}

-(void)expandTableHeaderView:(id)sender{

    [self.tblView beginUpdates];
    NSInteger section = [sender tag];
     UIView *view = (UIView *)[_header_view viewWithTag:[sender tag]]; //RETURNS nil
        NSArray *arr = [view subviews]; //RETURNS nil

}

我不知道为什么会这样?请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

在此方法中,您将创建新的headerView。现在,此时headerView中没有子视图。 您正在设置headerView.btn.tag,但您没有在headerView中添加按钮,图像也是如此。

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    _header_view = [[HeaderViewSection alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    _header_view.tag = section+5000;
UIButton *button = [UIButton alloc] init];//set frame also
button.tag = section+5000;
 [button addTarget:self action:@selector(expandTableHeaderView:)  forControlEvents:UIControlEventTouchUpInside];
[header_view addSubView:button];

   //Do same like image view

}

Edied: 只有当您点按按钮时,-(void)expandTableHeaderView:(id)sender{ }方法才会调用。 Button是headerView的子视图。您可以通过调用此类superView方法来获取标题视图

UIView *view = (UIView*)[sender superView];
view.frame = // new frame

现在查看是headerView,您可以更改其框架以扩展或您想要的任何内容。 您可以像这样获取其子视图

NSArray *array = [view subViews];
for(UIView *v in array){
if([v isKindOfClass:[UIImage class]]){
//v is imageview change image if you want
}