2013-11-20 2 views
1

Я пытаюсь создать (не очень) пользовательский UITableView с кнопкой в ​​левой части ячейки и текст справа от кнопки.IOS - как мне переместить UILabel в UITableViewCell?

Я пытаюсь вычислить, где положить UILabel, который является частью ячейки, но изменение кадра не имеет эффекта (и оно даже не вычисляется - все нули).

Мой вопрос: когда размер рамки для вычисленной метки? (Так что изменения будут иметь эффект).

Это правильный способ сделать это?

Фрагменты кода ниже. Во-первых от клеточной инициализации (вызывается в ответ на dequeueReusable ... и да, «buttonColor», «onTapSel», «buttonFrame» и «buttonColor» являются «переменными-члены (Файл статических Глобал)

- (id)initWithStyle: (UITableViewCellStyle)style 
    reuseIdentifier: (NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 

    if (nil == buttonColor) 
    { buttonColor = kDefaultCellButtonColor; } 

    if (nil == onTapSel) 
    { onTapSel = @selector(defaultCellButtonTapped:); } 

    if (self) 
    { 
     EGCellButton * cellButton = (EGCellButton *)[[EGCellButton alloc ] initWithFrame:buttonFrame ]; 
     cellButton.backgroundColor = buttonColor; 
     [cellButton setTitle:buttonLabel forState:UIControlStateNormal]; 
     [cellButton addTarget:self action:(onTapSel) forControlEvents: UIControlEventTouchUpInside]; 
     [self setCellButton:cellButton]; 

     float xx = buttonFrame.origin.x + buttonFrame.size.width + 5; 
     CGRect frame = self.textLabel.frame; 
     frame.origin.x += xx; 
     self.textLabel.frame = frame; 
     [self addSubview:cellButton]; 
    } 
    return self; 
} 

и теперь от cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"EGButtonTableCellID"; 
    EGButtonTableCell * cell = (EGButtonTableCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
    cell.cellButton.indexPath = indexPath; 

    // Configure the cell... 

    cell.textLabel.text = @"abcdefghijklmnopqrstuvwxyz"; 

    float xx = cell.cellButton.frame.origin.x + cell.cellButton.frame.size.width + 5; 
    CGRect frame = cell.textLabel.frame; 
    frame.origin.x += xx; 
    cell.textLabel.frame = frame; 

    return cell; 
} 

в результате того, что на левой стороне ячейки (по назначению) появляется кнопка, но первое письмо, которое я вижу в этикетке «г», так первые 6 символов скрыты за кнопкой (не предназначены).

Когда я выгружаю значения в кадре, все, кроме origin.x, равны нулю в обоих методах.

Это должно сработать, да? нет? почему нет? и т.д. Спасибо всем очень!

: пн:

+0

Где вы настройки значение buttonFrame? – rdelmar

+0

Попытка создать пользовательские ячейки в 'cellForRow ...' - огромная боль. Я знаю, что сначала кажется проще, но вы всегда должны просто подклассифицировать UITableViewCell и делать это именно так. (Следуйте за ответом Мэгги.) –

ответ

1

Установить рамку для UILabel и UIButton в layoutSubviews методе пользовательских UITableViewCell

См Apple, Документация по теме:

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

+1

** Важно **: Убедитесь, что вы вызываете '[super layoutSubviews]' в качестве первой строки вашей реализации. – rmaddy

0

Вы можете создать пользовательский UITableViewCell, получить доступ к объектам в классе или реализовать методы.

CustomCell.h

#import <UIKit/UIKit.h> 

@interface CustomCell : UITableViewCell 

@property (nonatomic, retain) UILabel *customCellLabel; 
@property (nonatomic, retain) UIButton *customCellButton; 

@end 

CustomCell.m

#import "TLCell.h" 
@implementation CustomCell 

@synthesize customCellLabel, customCellButton 
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     customCellLabel = [[UILabel alloc] init]; 
     customCellLabel.frame = CGRectMake(180, 0, 60, 30); 
     [self addSubview:customCellLabel]; 

     customCellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     customCellButton.frame = CGRectMake(0, 0, 60, 30); 
     [self addSubview:customCellButton]; 
    } 
    return self; 
} 

@end 

CustomTableView.m

/* --- */ 
- (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.customLabel setText:@"hello"]; 
    // [cell. 
    [cell.customButton addTarget:self action:@selector(yourMethod:) forControlEvents:UIControlEventTouchUpInside]; 
} 
/* --- */ 
Смежные вопросы