Пользовательский пример tableViewCell с изображениями и ярлыками - PullRequest
0 голосов
/ 11 марта 2011

Я создаю пользовательский UITableViewCell, прежде чем приступить к его созданию, я прочитал много статей о нем и начинаю создавать свой собственный CustomTableViewCell.

В моем собственном TableViewCell у меня есть 4 поля:

  1. UILabel * cellTitle
  2. UILabel * cellDateTime
  3. UIView * cellMainImage
  4. UIImageView * arraow image

Вот как выглядит мой TableViewCell:enter image description here

А вот код: CustomTableViewCell.h

#import <UIKit/UIKit.h>

#define TAGS_TITLE_SIZE     20.0f
#define TITLE_LABEL_TAG     1
#define DATA_TIME_LABEL_TAG 5
#define ARROW_IMAGE_TAG     6
#define MAIN_IMAGE_TAG      7

// Enumeration for initiakization TableView Cells
typedef enum {
    NONE_TABLE_CELL      = 0,
    NEWS_FEED_TABLE_CELL = 1,
    TAGS_TABLE_CELL      = 2
}TableTypeEnumeration;

// Class for Custom Table View Cell.
@interface CustomTableViewCell : UITableViewCell {
    // Title of the cell.
    UILabel*     cellTitle;
    UILabel*     cellDataTime;
    UIView*      cellMainImage;
    UIImageView* cellArrowImage;
}

// Set the title of the cell.
- (void) SetCellTitle: (NSString*) _cellTitle;
- (void) SetCellDateTime: (NSString*) _cellDataTime;

- (void) ReleaseCellMainImage;

- (void) InitCellTitleLable;
- (void) InitCellDateTimeLabel;
- (void) InitCellMainImage;



// Init With Style (With additional parametr TableTypeEnumeration)
- (id)initWithStyle: (UITableViewCellStyle)style reuseIdentifier: (NSString *)reuseIdentifier tableType:(TableTypeEnumeration)tabletypeEnum;

@end

А вот код: CustomTableViewCell.m

#import "CustomTableViewCell.h"

@implementation CustomTableViewCell


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    return [self initWithStyle:style reuseIdentifier:reuseIdentifier tableType:NONE_TABLE_CELL];
}

- (id)initWithStyle: (UITableViewCellStyle)style reuseIdentifier: (NSString *)reuseIdentifier tableType:(TableTypeEnumeration)tabletypeEnum {
    // Get Self.
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        // Switch table View Cells
        switch(tabletypeEnum) {
            case NEWS_FEED_TABLE_CELL: {

                // Create Cell Title Text
                cellTitle = [[UILabel alloc] initWithFrame:CGRectMake(75.0f, 2.5f, 180.0f, 33.0f)];
                cellTitle.tag           = TITLE_LABEL_TAG;
                cellTitle.font          = [UIFont boldSystemFontOfSize: 13.0f];
                cellTitle.lineBreakMode = UILineBreakModeWordWrap;
                cellTitle.numberOfLines = 0;
                cellTitle.textAlignment = UITextAlignmentLeft;
                cellTitle.textColor     = [UIColor blackColor];
                [self.contentView addSubview:cellTitle];
                [cellTitle release];

                // Create Cell Description Text.
                cellDataTime = [[UILabel alloc] initWithFrame:CGRectMake(135.0f, 38.0f, 100.0f, 15.0f)];
                cellDataTime.tag           = DATA_TIME_LABEL_TAG;
                cellDataTime.font          = [UIFont italicSystemFontOfSize: 12.0f];
                cellDataTime.textAlignment = UITextAlignmentLeft;
                cellDataTime.textColor     = [UIColor blackColor];
                cellDataTime.lineBreakMode = UILineBreakModeWordWrap;
                [self.contentView addSubview:cellDataTime];
                [cellDataTime release];

                // Create Cell Arrow Image.
                cellArrowImage = [[UIImageView alloc] initWithFrame:CGRectMake(260.0f, 7.0f, 40.0f, 49.0f)];
                cellArrowImage.tag             = ARROW_IMAGE_TAG;
                cellArrowImage.backgroundColor = [UIColor whiteColor];
                cellArrowImage.image           = [UIImage imageNamed:@"Grey Arrow.png"];;
                [self.contentView addSubview:cellArrowImage];
                [cellArrowImage release];

                // Create Cell Main Image.
                cellMainImage = [[[UIView alloc] initWithFrame:CGRectMake(2.0f, 2.5f, 55.0f, 50.0f)] autorelease];
                cellMainImage.tag = MAIN_IMAGE_TAG;
                [self.contentView addSubview:cellMainImage];


                break;
            }
            case TAGS_TABLE_CELL: {

                // Create and initialize Title of Custom Cell.
                cellTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, (44 - TAGS_TITLE_SIZE)/2, 260, 21)];
                cellTitle.backgroundColor      = [UIColor clearColor];
                cellTitle.opaque               = NO;
                cellTitle.textColor            = [UIColor blackColor];
                cellTitle.highlightedTextColor = [UIColor whiteColor];
                cellTitle.font                 = [UIFont boldSystemFontOfSize:TAGS_TITLE_SIZE];
                cellTitle.textAlignment        = UITextAlignmentLeft;
                [self.contentView addSubview:cellTitle];
                [cellTitle release];

                break;
            }
            default: break;
        }
    }
    return self;


}

- (void) ReleaseCellMainImage {
    [cellMainImage release];
}

- (void) InitCellTitleLable {
    cellTitle = (UILabel *)[self.contentView viewWithTag:TITLE_LABEL_TAG];
}

- (void) InitCellDateTimeLabel {
    cellDataTime = (UILabel *)[self.contentView viewWithTag:DATA_TIME_LABEL_TAG];
}

- (void) InitCellMainImage {
    //UIView* oldImage = [self.contentView viewWithTag:MAIN_IMAGE_TAG];
    //[oldImage removeFromSuperview];
}


- (void) SetCellTitle: (NSString*) _cellTitle {
    cellTitle.text = _cellTitle;
}


- (void) SetCellDateTime: (NSString*) _cellDataTime {
    cellDataTime.text = _cellDataTime;
}

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


- (void)dealloc {

    // Call base delloc
    [super dealloc];
}

@end

Теперь, когда яиспользуйте мой CustomTableViewCell в коде программы, память моего iphone всегда увеличивается !!!Каждый раз, когда я открываю tableView, память увеличивается на 2 МБ, а когда я открываю и закрываю tableView в течение 10 раз, она становится больше, чем 30 МБ !!!Что я могу сделать ???

И еще один вопрос

Как я могу получить событие, когда пользователь, например, нажимает на мое изображение в пользовательской ячейке ???

Ответы [ 3 ]

0 голосов
/ 11 марта 2011

Реализуете ли вы повторное использование ячейки при создании ячейки? В коде нет указаний на то, что вы пытаетесь удалить из очереди многоразовую ячейку из UITableView до init, хотя это может быть в самом табличном представлении. Как видно из поста Правинса, есть попытка удалить из очереди ячейку, и только если она возвращает ноль, инициализируется ячейка.

В результате вы можете создавать новый объект ячейки каждый раз, когда эта конкретная ячейка появляется в поле зрения. Принято ли повторное использование ячеек в табличном представлении?

Какой код содержится в методе делегата табличного представления - tableView: cellForRowAtIndexPath?

0 голосов
/ 11 марта 2011

В дополнение к рассмотрению повторного использования ячеек, как говорят другие, если использование памяти увеличивается с каждым открытием, у вас может быть утечка памяти. Возможно, ваше представление, которое создает таблицу, не освобождает ее при освобождении.

0 голосов
/ 11 марта 2011

Вы не используете свои клетки повторно.Следовательно, новая ячейка создается при каждой прокрутке.

В вашем делегате вам необходимо воссоздать ячейку следующим образом:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (nil == cell) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:CellIdentifier] autorelease];
}



return cell; 
...