如何增加和调整iPhone中的tableview单元格?

时间:2013-08-31 10:35:36

标签: iphone ios objective-c uitableview

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    return 50; 
} 

在这个地方,我想动态添加一个按钮来增加单元格的高度,所以当用户点击该按钮时,应该增加单元格的高度,然后再次单击以调整高度。

我想要像:

-(void)IncreaseCell
{
    UIButton *DownArrow = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [DownArrow addTarget:self 
                  action:@selector(IncreaseCell:)
        forControlEvents:UIControlEventTouchDown];
    //[DownArrow setTitle:@"Arrow" forState:UIControlStateNormal];
    DownArrow.frame = CGRectMake(121.0, 112.0, 72.0, 37.0);
    [cell.contentView addSubview:DownArrow];

    UIImage *buttonDown = [UIImage imageNamed:@"friendsDownArrowButton.png"];
    [DownArrow setBackgroundImage:buttonDown forState:UIControlStateNormal];
    [cell.contentView addSubview:DownArrow];   
}

4 个答案:

答案 0 :(得分:1)

  1. 您需要创建一个NSMutableArray作为实例变量,在其中跟踪您想要“增加”的所有单元格。

    @interface YourTableViewController : UITableViewController {
        NSMutableDictionary *increasedRows;
    }
    

    记得分配/初始化该变量。

  2. 让你的细胞增加:

    -(void)increseCell: (BOOL)status forIndexPath: (NSIndexPath*)indexPath {
        [increasedRows setObject:[NSNumber numberWithBool:status] forKey: indexPath];
    
        [self.tableView beginUpdates]; //Delete if you don't want it animated
        [self.tableView endUpdates]; //Delete if you don't want it animated
    
        // [self.tableView reloadData]; //Uncomment if you don't want it animated
    }
    
  3. 您更改了tableView: heightForRowAtIndexPath:声明,以便为indexPath检查此词典。

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        // Check if cell is increased, return custom height
        if([[increasedRows objectForKey:indexPath] boolValue]) {
            return 150;
        }
        // Cell isn't increased so return regular height
        return 50;
    }
    
  4. 此方法允许您单独为每一行执行此操作,并允许您为其设置动画。

答案 1 :(得分:0)

您所要做的就是声明一个变量:

@interface yourViewController ()
{
    CGFloat cellSize;
}

在您的heightForRowAtIndexPath:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
       return cellSize; 
}  

viewDidLoad

-(void)viewDidLoad
{
     [super viewDidLoad];
     cellSize = 50;
}

并在increaseCell:

中结束
-(void)IncreseCell {
     cellSize += 10;
     [self reloadData];
}

答案 2 :(得分:0)

您需要更改heightForRowAtIndexPath

的实施方式

添加一些存储,如数组,其中包含指示行是否展开的标志。当点击按钮时,获取它所在的单元格的索引路径并编辑数组内容以设置/取消设置该标志。重新加载表视图(或更改的索引路径的行)。

答案 3 :(得分:0)

我在我的一个项目中所做的是创建了一个自定义单元格并静态添加子视图

第一个场景非折叠视图 自定义单元格仅显示单击按钮,通过增加单元格大小显示扩展视图..

即点击按钮,你应该使用函数增加单元格的大小..

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

 BOOL check=[[booleanArrayofrows objectAtIndex:indexPath.row] boolValue];

        if (check)
        {
            return 180; ..expanded view height
        }
        return 40; collapse view height
    } 
}