gpt4 book ai didi

ios - 如何在 UITableView Cell 中以编程方式创建 n 个 UIButton?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:56:47 24 4
gpt4 key购买 nike

我正在尝试创建一个带有 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' 个 UIButton ?? UIButton 宽度取决于其文本内容

最佳答案

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

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)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 action:@selector(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com