嘿,我一直在寻找这个问题,并且在我的问题中也找到了一些主题,但我显然没有得到我做错的事情,所以这里有我的问题我有一个UITableViewCell,并希望向它添加一个UITextField。所以我设置了一个textField并将其添加到cellForRowAtIndexPathRow:中的单元格中,但是当我选择行或者恰好是textField没有键盘或显示时,我也看不到占位符。
这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectZero];
textField.delegate = self;
textField.placeholder = NSLocalizedString(@"Description", nil);
[cell addSubview:textField];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
return nil;
}
感谢您的帮助;)
答案 0 :(得分:1)
简单:不要这样做。
相反 - 子类UITableViewCell,让它有一个xib文件并将你的gui组件放在那里。然后使用重用标识符注册xib,并将出列的单元格转换为您的类型。
如果直接向细胞添加子视图,则会出现回收问题。 (即多个子视图堆叠在一起)。
有很多关于tableviews的指南以及如何正确地完成它。
您还可以使用故事板中的原型单元格,这非常简单。虽然这不允许您重复使用多个ViewControllers中的单元格而不重复故事板中的原型单元格。
此外,initWithFrame几乎是石头之物。如果您在开始使用其他屏幕尺寸时不想发疯,则应使用约束。 (即iphone 6和6plus + ipad)
答案 1 :(得分:0)
因为您调用了initWithFrame:CGRectZero。 CGRectZero表示origin.x = 0.0 orgin.y = 0.0,size.width = 0.0和size.height = 0.0。因此看不见。你应该调用initWithFrame:CGRectMake(0.0,0.0.100.0.40.0)。 更好的方法是使用xib进行自定义单元设计。
答案 2 :(得分:0)
在此行UITextField *textField = [[UITextField alloc] initWithFrame:CGRectZero];
上,您为自己的框架提供CGRectZero
值,这样就会设置width
,height
,x position
和{{1} } y position
基本上意味着它不会出现。因此,您需要做的是使用0.0
CGRectMake(x, y, width height)
创建一个有效的框架。这应该创建具有正确帧的UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, 100, 20)];
的有效新实例。为了更好地理解UITextField
的工作原理,阅读documentation from UIView
也许值得。我说initWithFrame:
文档,因为UIView
从UITextField
继承了此方法。
答案 3 :(得分:0)
我看到你用一个归零的框架(CGRectZero
)初始化了textField。尝试传递一个实际的框架,例如:
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 15, 75, 20)]; //x, y, width, height
此外,您应该将子视图添加到单元格的contentView:
[cell.contentView addSubview:textField];