Ios 如何在UITableViewCell上添加按钮
我有一个预填充的Ios 如何在UITableViewCell上添加按钮,ios,objective-c,uitableview,Ios,Objective C,Uitableview,我有一个预填充的UITableViewCell,该单元格上有标签和UITextField。假设我有一个标签为“map”的单元格,并且我想在该单元格上添加按钮,我如何才能做到这一点? 我试过了,但没用。 代码如下: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier =
UITableViewCell
,该单元格上有标签和UITextField
。假设我有一个标签为“map”的单元格,并且我想在该单元格上添加按钮,我如何才能做到这一点?我试过了,但没用。
代码如下:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"rateSheetCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (indexPath.row == 0)
{
((UILabel*)[cell viewWithTag:100]).text = @"Title";
((UITextField*)[cell viewWithTag:101]).placeholder = @"Title";
((UITextField*)[cell viewWithTag:101]).text = arrayResourceColumns[indexPath.section][indexPath.row][@"resource_title"];
((UITextField*)[cell viewWithTag:101]).keyboardType = UIKeyboardTypeDefault;
}
else
{
if([arrayResourceColumns[indexPath.section][indexPath.row][@"label"] isEqualToString:@"OT ($)"]){
NSInteger desiredLabel = (NSInteger)(arrayResourceColumns[indexPath.section][indexPath.row][@"label"]);
//NSString *desiredLabel = arrayResourceColumns[indexPath.section][indexPath.row][@"label"];
NSLog(@"Label is>>>>--------%ld", (long)desiredLabel);
if (indexPath.row == desiredLabel ) {
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
[b setFrame:CGRectMake(0, 0, 50, 50)];
}
}
((UILabel*)[cell viewWithTag:100]).text = arrayResourceColumns[indexPath.section][indexPath.row][@"label"];
((UITextField*)[cell viewWithTag:101]).placeholder = ((UILabel*)[cell viewWithTag:100]).text;
((UITextField*)[cell viewWithTag:101]).text = arrayResourceColumns[indexPath.section][indexPath.row][@"attribute_value"];
if (indexPath.row == [arrayResourceColumns[indexPath.section] count] - 1)
{
((UITextField*)[cell viewWithTag:101]).enabled = NO;
}
}
}
有几种方法可以在
UITAbleViewCell
上添加按钮:1) 如果您使用的是故事板,您可以使用按钮创建单元原型,然后使用
标记属性
2) 子类UITableViewCell
并在init
3) 将按钮添加到表格视图中的单元格:cellforrowatinexpath:
方法
UPD
如何使用故事板自定义UITableViewCell
@HermannKleckerUITableViewCell
的教程是一个UIView
,而不是UIViewController
,没有viewDidLoad
,init
是添加其子视图的正确位置。选项3是可能的,但对初学者来说并不可取,虽然看起来很容易,但事实并非如此。当然,除非按钮在所有单元格上。然后cellForRow。。。这是个不错的地方。但是,如果按钮不在所有单元格上,则需要一些智能编码以及重复使用逻辑,以避免出现奇怪的效果,例如当单元格变为可见时每次向单元格添加一个按钮,或者滚动时按钮出现在重复使用的单元格中等。您似乎使用标记100和101来访问单元格的子视图。但是你把它们放在哪里了?它们应该添加在单元格==nil
案例中,顺便说一句。@Khanh标签是textlabel和textfield的,textlabel和textfield是在uitableviewcell原型中添加的storyboard@user1699419最好使用自己的自定义表视图单元格。在这里面,你可以添加子视图,如UIButton、UILabel和UIExtField等。。。你找到解决方案了吗?@AnandGautam不,我没有找到你:(@user1699419)你以前在自定义表视图单元格上工作过吗?请参阅这些链接