Создайте UITableView на основе пользовательской ячейки

У меня проблема. Я хочу, чтобы в моей таблице отображалась моя пользовательская ячейка. Каждая ячейка содержит кнопку (см. прикрепленный файл)

введите здесь описание изображения

В методе cellForRowAtIndexPath я возвращаю пользовательскую ячейку. Пользовательская ячейка содержит UIButton, как показано на прикрепленном изображении.

Моя проблема заключается в следующем - когда я нажал кнопку, она должна загореться (до красного цвета), а другая кнопка должна затухнуть (до синего цвета). Как установить связь между объектами?

Буду рад любым ответам! Спасибо!


person Matrosov Alexander    schedule 12.12.2011    source источник


Ответы (1)


Я решил эту проблему следующим образом:

Это моя реализация класса UITableViewController.

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

    static NSString *CellIdentifier = @"CustomCell";
    CustomCell *cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    if (cell == nil) {
        cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.delegate = self;
    [cells addObject:cell];

    // Configure the cell...

    return cell;
}

- (void)mustDeselectWithout:(CustomCell *)cell{
    for (CustomCell * currentCell in cells) {
        if(currentCell != cell){
            [currentCell deselect];
        }
    }
}

Как видите, когда я создаю ячейки, я возвращаю пользовательскую ячейку в методе cellForRowAtIndexPath.

Это класс пользовательской ячейки

.h

#import <UIKit/UIKit.h>
#import "ProtocolCell.h"

@interface CustomCell : UITableViewCell {
    UIButton * button;
}
@property(nonatomic, assign) id<ProtocolCell> delegate;
- (void)select;
- (void)deselect;
@end

И м

#import "CustomCell.h"


@implementation CustomCell
@synthesize delegate;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(5, 5, 25, 25)];
        [button setBackgroundColor:[UIColor blueColor]];
        [button addTarget:self action:@selector(select) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:button];
    }
    return self;
}

- (void)select{
    [button setBackgroundColor:[UIColor redColor]];
    [delegate mustDeselectWithout:self];
}

- (void)deselect{
    [button setBackgroundColor:[UIColor blueColor]];    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)dealloc
{
    [super dealloc];
}

@end

Мой класс UITableViewController реализует протокол ProtocolCell. Когда я нажимаю на кнопку, мой делегат вызывает метод mustDeselectWithout и отменяет выбор всех кнопок в моем массиве без текущей кнопки.

#import <Foundation/Foundation.h>
@class CustomCell;

@protocol ProtocolCell <NSObject>
- (void)mustDeselectWithout:(CustomCell *)cell;
@end

Это моя реализация. Если вы можете сделать комментарии, я буду рад. Потому что я не знаю, правильное это решение моей проблемы или нет. Спасибо!

person Matrosov Alexander    schedule 14.12.2011