【发布时间】:2015-07-31 16:18:21
【问题描述】:
在我的应用程序中,行从不同的视图添加到我的TableView。当用户添加行时,用户被带回TableView。问题是之前输入的文本不再显示。
我可以使用NSMutableDictionary 加载它,但用户看不到它。关于我应该做什么的任何想法?我应该添加什么代码以及应该在哪里添加它?非常感谢!
这是来自tableview 方法的代码。我认为修复程序会在这里某个地方。
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.wtf = [[UITextField alloc]init];
NSUInteger count =0;
for (NSMutableDictionary *search in dataForAllRows){ //this just helps me pull the right data out of an array of NSMutableDictionary's
if ([search valueForKey:@"indexSection"] == [NSNumber numberWithInteger:(indexPath.section -1)]) {
if ([search valueForKey:@"indexRow"] == [NSNumber numberWithInteger:indexPath.row]) {
NSMutableDictionary *match = [dataForAllRows objectAtIndex:count];
[cell.wtf setText:[match objectForKey:@"wtf"]];
NSLog(@"%@",cell.wtf.text); // this outputs the correct value in the command line
}
}
count++;
}
}
}
这是我的 CustomCell.m 的代码
#import "CustomCell.h"
@implementation CustomCell
@synthesize wtf, cellPath;
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(void)layoutSubviews{
wtf = [[UITextField alloc] initWithFrame:CGRectMake(7, 3, 65, self.contentView.bounds.size.height-6)];
self.wtf.delegate = self;
[wtf setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[wtf setAutocorrectionType:UITextAutocorrectionTypeNo];
[wtf setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[wtf setBorderStyle:UITextBorderStyleRoundedRect];
wtf.textAlignment = NSTextAlignmentCenter;
wtf.keyboardType = UIKeyboardTypeNumberPad; //
[wtf setAutocapitalizationType:UITextAutocapitalizationTypeWords];
[wtf setPlaceholder:@"enter"];
[self.contentView addSubview:wtf];
}
【问题讨论】:
-
两项改进将使您的生活更轻松:(1) 单元格是否在故事板/ib 中定义?如果没有,请执行此操作,(2) 数据源 (dataForAllRows) 的简单转换将澄清代码并避免每次滚动到视图中时对数据进行全面搜索。
-
@danh 不,我的单元格没有在故事板/ib 中定义。我会看看如何做到这一点。这是我问题的根源吗?对不起,如果我的一些问题是基本的。我对此有点陌生。
-
您能否将
cell.wtf.backgroundColor = [UIColor greenColor];添加到您的代码中,以确保将文本字段正确添加到单元格中。并分享将 UITextfield 添加到单元格的代码。 -
在某种程度上是的。不在 IB 中定义单元会迫使您在代码中执行此操作,这更容易出错,而且您的代码似乎省略了几个必要的步骤。请参阅下面的答案。
-
@williamb 当我将
cell.wtf.backgroundColor = [UIColor greenColor];添加到cellForRowAtIndexPath时什么也没发生。当我在我的 CustomCell.m 文件中添加该代码时,它工作并且背景颜色为绿色。我将UITextfield添加到我的CustomCell.m 文件中的单元格中。我很快就会将该代码添加到我的问题中。再次感谢您的帮助。
标签: ios objective-c iphone uitableview uitextfield