質問

I have a custom UITableViewCell, lets call it CustomCell. All I need is to pass an argument when creating it, lets say a NSURL.

This is what I've done so far in my ViewController:

In viewDidLoad:

[myTableView registerClass: [CustomCell class] forCellReuseIdentifier: @"CustomItem"]

In tableView:cellForRowAtIndexPath:

static NSString *myIdentifier = @"CustomItem"
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:myIdentifier] 

All this works great, but I need to configure the cell with this one NSURL, but just once, not every time cellForRowAtIndexPath is called. I've noticed that initWithStyle: reuseIdentifier: in CustomCell is being call just once, but how can I add the NSURL with this call?

役に立ちましたか?

解決

You just load an NSArray inside viewDidLoad. Inside cellForRowAtIndexPath: you add the URL from your NSArray and insert it into the UITableViewCell.

static NSString *myIdentifier = @"CustomItem"
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:myIdentifier]
[cell.labelURL setText:_arrayURLs[indexPath.row]];

Everything you have to do is to add a new property to your CustomCell called labelURL and connect it with a UILabel inside your UIStoryboard or xib file.

And think about, you can't just set them once. UITableViewCell will reuse its UITableViewCells and will always set another value multiple times to the same object. Thats why you have to do it this way and not only once.

他のヒント

UITableViewCell of the same type should be reused using cellForRowAtIndexPath:. If you want a property to stay the same it should go in area A. If you want it to change every cell it should go in area B

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CustomCell";
    CustomCell *cell = 
      [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault 
                                reuseIdentifier:CellIdentifier];
       // (A) everything inside here happens once 
       // for example

       cell.textLabel.backgroundColor = [UIColor redColor];
    }

    // (B) everything here happens every reuse of the cell
    // for example

    cell.textLabel.text = [NSString stringWithFormat:@"%li",
                            (long)indexPath.row];
    return cell;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top