2013-04-14 2 views
0

Попытка разместить UILabel, содержащий дату в правом нижнем углу ячейки, будь то на iPhone или iPad.UITableViewCell frame.size.width - это то же самое для ipad и iphone?

Вот что я в настоящее время, что мне нужно сделать, чтобы получить фактическую ячейку size.width, пытался делать cell.bounds.size.width, а также, то же самое значение ли iPhone или IPad:

float xValue = cell.frame.size.width - 100; 
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(xValue, 20.0f, 100, 17.0f)]; 
[nameLabel setTag:1]; 
[nameLabel setFont:[UIFont boldSystemFontOfSize:15.0]]; 
nameLabel.textColor = [UIColor grayColor]; 
nameLabel.text = @"05-12-13"; 
// custom views should be added as subviews of the cell's contentView: 
[cell.contentView addSubview:nameLabel]; 

ETA, здесь есть все пользовательские класс клеток, может быть, кто-то может увидеть, что вызывает дублирование метки:

@interface VideoTableViewCell : UITableViewCell 

+ (VideoTableViewCell *)cellForTableView:(UITableView *)tableView; 
+ (CGFloat)heightForVideo:(id<VideoProtocol>)video; 
- (void)updateCellForVideo:(id<VideoProtocol>)video; 

@end 

#define MARGIN 10 

@implementation VideoTableViewCell 

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

     self.textLabel.font = [UIFont boldSystemFontOfSize:14]; 

     self.detailTextLabel.font = [UIFont systemFontOfSize:13]; 
     self.textLabel.numberOfLines = 2; 
     self.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    } 
    return self; 
} 

+ (VideoTableViewCell *)cellForTableView:(UITableView *)tableView { 

    NSString *identifier = @"TweetCell"; 
    VideoTableViewCell *cell = (VideoTableViewCell *)[tableView 
                dequeueReusableCellWithIdentifier:identifier]; 
    if (cell == nil) { 
     cell = [[VideoTableViewCell alloc] 
       initWithStyle:UITableViewCellStyleSubtitle 
       reuseIdentifier:identifier]; 
    } 

    return cell; 
} 

- (void)layoutSubviews { 

    [super layoutSubviews]; 
    CGRect cvf = self.contentView.frame; 
    self.imageView.frame = CGRectMake(0.0, 
             0.0, 
             cvf.size.height-1, 
             cvf.size.height-1); 
    self.imageView.contentMode = UIViewContentModeScaleAspectFit; 

    CGRect frame = CGRectMake(cvf.size.height + MARGIN, 
           self.textLabel.frame.origin.y, 
           cvf.size.width - cvf.size.height - 2*MARGIN, 
           self.textLabel.frame.size.height); 
    self.textLabel.frame = frame; 

    frame = CGRectMake(cvf.size.height + MARGIN, 
         self.detailTextLabel.frame.origin.y, 
         cvf.size.width - cvf.size.height - 2*MARGIN, 
         self.detailTextLabel.frame.size.height); 
    self.detailTextLabel.frame = frame; 
} 

- (void)setDateLabelWithDate:(NSDate *)date { 


    float xValue = self.frame.size.width - 70; 
    // create a custom label:          x  y width height 
    UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(xValue, 40.0f, 100, 12.0f)]; 
    dateLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin; 
    [dateLabel setFont:[UIFont boldSystemFontOfSize:13.0]]; 
    dateLabel.textColor = [UIColor grayColor]; 

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"MM-dd-yy"]; 
    NSString *dateString = [dateFormatter stringFromDate:date]; 
    dateLabel.text = dateString; 
    [self.contentView addSubview:dateLabel]; 
} 

+ (CGFloat)heightForVideo:(id<VideoProtocol>)video { 

    //create a dummy cell 
    VideoTableViewCell *sampleCell = [[VideoTableViewCell alloc] 
             initWithStyle:UITableViewCellStyleSubtitle 
             reuseIdentifier:nil]; 
    [sampleCell updateCellForVideo:video]; 

    //calculate the sizes of the text labels 
    CGSize textSize = [video.title sizeWithFont: [VideoTableViewCell textLabelFont] 
            constrainedToSize:sampleCell.textLabel.frame.size 
             lineBreakMode:UILineBreakModeWordWrap]; 
    CGFloat minHeight = 51 + 10; //image height + margin 
    return MAX(textSize.height + 20, minHeight);  
} 

+ (UIFont *)textLabelFont { 
    return [UIFont systemFontOfSize:13]; 
} 

- (void)updateCellForVideo:(id<VideoProtocol>)video { 

    // set the text to the date with the tweet text 
    self.textLabel.text = video.title; 
    id<VideoAttrProtocol> speaker = [[video.speakers allObjects] objectAtIndex:0]; 
    self.detailTextLabel.text = speaker.name; 
    [self setDateLabelWithDate:video.post_date]; 
    NSURL *url = [NSURL URLWithString:video.thumbnail];  
    [self.imageView setImageWithURL:url 
        placeholderImage:[UIImage imageNamed:@"Logo.png"]]; 
} 


@end 
+0

Вам нужно показать метод tableView: cellForRowAtIndexPath: 'в вашем контроллере вида. – rmaddy

ответ

2

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

Прежде, чем добавить ярлык для представления содержимого, добавьте:

Обновления на основе всех отправленный код:

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

Вы вызываете этот метод от updateCellForVideo: и, возможно, от вашего контроллера вида (вы не показываете этот код).

Вам необходимо обновить код, чтобы вы не добавляли новую метку в ячейку каждый раз, когда вызывается setDataLabelWithDate:. Добавляйте ярлык только один раз.

+0

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

+0

Похоже, вы добавляете ярлык снова и снова. Просто добавьте его в ячейку один раз. – rmaddy

+0

Я создаю этот UILabel и добавляю его в ячейку для каждой созданной ячейки. Может быть, это потому, что я делаю шаблон повторного использования ячеек с помощью dequeueReusableCellWithIdentifier? –

Смежные вопросы