OStack程序员社区-中国程序员成长平台

标题: ios - 如何在 UITableView Cell 中以编程方式创建 n 个 UIButton? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 16:56
标题: ios - 如何在 UITableView Cell 中以编程方式创建 n 个 UIButton?

我正在尝试创建一个具有 n 个按钮的 UITableView 取决于后端 JSON 数据。

我附上了一张图片,我知道如何在 UITableViewCell 上创建 UIButton,但我不知道如何将它们正确放置在 UITableViewCell 中。

UIButton 用于 UITableViewCell

UIButton *continuebtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 100, view1.frame.size.width-20, 40)];
[continuebtn setBackgroundColor:[UIColor grayColor]];
[continuebtn setTitle"Continue" forState:UIControlStateNormal];
continuebtn.layer.cornerRadius = 10;
continuebtn.layer.borderWidth =1.0;
continuebtn.layer.borderColor = [UIColor blackColor].CGColor;
[continuebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

enter image description here

如何在 UITableViewCell 上放置 'n' 个 UIButtonUIButton 宽度取决于它的文本内容



Best Answer-推荐答案


如果您想在单元格中垂直放置按钮,请使用以下建议:

UITableviewCell 的高度取决于按钮的数量。实现 heightForRowAtIndexPath 方法如下:

- (CGFloat)tableViewUITableView *)tableView heightForRowAtIndexPathNSIndexPath *)indexPath {
    return 100.0f + (buttonsArray.count*buttonHeight+buttonsHeightSeparator);

    //change 100.0f with height that is required for cell without buttons
    //buttonHeight is a static float representing value for height of each button
    //buttonHeightSeparator is a static float representing separation distance between two buttons
}

在您的 cellForRowAtIndexPath 方法中,您可以使用以下代码创建按钮:

for(int i=0; i<buttonsArray.count; i++) {
    UIButton *continuebtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 100+i*(buttonHeight+buttonsHeightSeparator), view1.frame.size.width-20, 40)];
    [continuebtn setBackgroundColor:[UIColor grayColor]];
    [continuebtn setTitle"Continue" forState:UIControlStateNormal];
    continuebtn.layer.cornerRadius = 10;
    continuebtn.layer.borderWidth =1.0;
    continuebtn.layer.borderColor = [UIColor blackColor].CGColor;
    [continuebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [continuebtn addTarget:self actionselector(continueBtnPressed forControlEvents:UIControlEventTouchUpInside]; //add target to receive button tap event
    [continuebtn setTag:i]; //to identify button
    [cell.contentView addSubview:continuebtn]; //add button to cell
}

关于ios - 如何在 UITableView Cell 中以编程方式创建 n 个 UIButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33496982/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4