weky weky -4 years ago 111
iOS Question

xcode ios - image in tableview section header

This is my code:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIImage *myImage = [UIImage imageNamed:@"photo.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage];
imageView.frame = CGRectMake(10,10,60,60);

if (section == 0){
return 0;
}else if (section == 1){
return 0;
}else if (section == 2){
return 0;
}else if (section == 3){
return 0;
}else if (section == 5){
return imageView;
}else{
return 0;
}
}


So the image appears but the problem is that the
imageView.frame
is not working, the photo size is appearing equal to the header height, how can i fix that?

Answer Source

When you implement the tableView:viewForHeaderInSection: method you must also implement the tableView:heightForHeaderInSection: method to return the desired header height:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 5) {
        return 70;
    } else {
        return 0;
}

And your viewForHeaderInSection method could be make better:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 5) {
        UIImage *myImage = [UIImage imageNamed:@"photo.png"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage];
        imageView.frame = CGRectMake(10, 10, 60, 60);
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 70];
        [view addSubview:imageView];

        return view;
    } else {
        return nil;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download