简体   繁体   中英

Setting UITextField placeholder in a cell from cellForRowAtIndexPath

I have a UITableView with a custom cell. Inside the cell I have a UITextField with some placeholder text. I would like to set the placeholder from cellForRowAtIndexPath, but when I try to set it, the placeholder just says (null). Additionally, I would like to format the placeholder as so, "Period (number the cell is in the tableView)" So for the cell nearest the top of the tableView, it would say "Period 1", the second from the top would say "Period 2". I can't figure out how to do the numbering or why the cell is printing null. Here is the code -

In the custom cell -

NSString *rowString = [NSString stringWithFormat:@"Period %@", self.rowNumber];
self.classText = [[UITextField alloc] init];
self.classText.delegate = self;
self.classText.placeholder = rowString;
self.classText.frame = CGRectMake(14, 3, 320, 40);
self.classText.keyboardAppearance = UIKeyboardAppearanceDark;
self.classText.font = [UIFont fontWithName:@"HelveticaNeue" size:17];
//[self.classText addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[self addSubview:self.classText];

In cellForRowAtIndex Path -

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    SchoolCell *cell = nil;
    static NSString *AutoCompleteRowIdentifier = @"AutoCompleteRowIdentifier";
    cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
    if (cell == nil) {
        cell = [[SchoolCell alloc]
                initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.rowNumber = @"test";

    return cell;
}

Where in the custom cell are you placing these lines of code that initialize classText? You are probably setting the rowNumber in the cellForRowAtIndex method after the classText is being initialized. Either create a custom init method that accepts the rowNumber as a parameter, or create a method in rowString that you can call later from cellForRowAtIndex after you set the rowNumber, and place the classText initialization code in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM