如何以编程方式在自定义单元格上添加自定义视图?

时间:2012-03-29 08:56:11

标签: objective-c uiview uitableview custom-controls

我有一个可能非常基本的问题。 我正在以编程方式构建一个没有Xib文件的自定义单元格。在我的CustomHell.m文件中,我基本上只有两个方法:initWithStyle和layoutSubviews。 我已设法以编程方式添加一些标签和一个按钮。现在我想添加一个特定的自定义视图 - FacebookLikeView(https://github.com/brow/FacebookLikeView) - 但我不知道该怎么做。 这是我的" initWithStyle:reuseIdentifier:

中的代码
    //StoreName Label
    storeName = [[UILabel alloc] init];
    storeName.textAlignment = UITextAlignmentLeft;
    storeName.font = [UIFont boldSystemFontOfSize: 16]; //12
    storeName.backgroundColor = [UIColor clearColor];
    storeName.adjustsFontSizeToFitWidth = YES;

    //checkIn Button
    checkInButton = [UIButton buttonWithType:UIButtonTypeCustom];
    checkInButton.frame = CGRectMake(203,10,86,25);
    [checkInButton setImage:[UIImage imageNamed:@"Check-In.png"] forState:UIControlStateNormal];
    [checkInButton addTarget:self.nextResponder action:@selector(addCheckin:) forControlEvents:UIControlEventTouchUpInside];
    checkInButton.backgroundColor = [UIColor redColor];

    //FACEBOOK
    facebookLikeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    facebookLikeButton.frame = CGRectMake(169,40,119,25);

    [self.contentView addSubview:storeName];
    [self.contentView addSubview:storeAddress];
    [self.contentView addSubview:subtitle];
    [self.contentView addSubview:checkInButton];
    [self.contentView addSubview:facebookLikeButton];
    //[self.contentView addSubview:likeButton];
return self;

这是我的layoutSubviews:

[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;

storeName.frame = CGRectMake(boundsX+10, 15, 190, 20);
storeAddress.frame = CGRectMake(boundsX+10, 42, 200, 40); 
subtitle.frame = CGRectMake(boundsX+10, 77, 280, 30);
likeButton.frame = CGRectMake(boundsX+199, 42, 50, 20);

头文件如下所示:

#import "FacebookLikeView.h"
@interface CustomCellHead : UITableViewCell
{
FacebookLikeView *likeButton;

UIButton *facebookLikeButton;
UIButton *checkInButton;
UILabel *storeName;
UILabel *storeAddress;
UILabel *subtitle;
}

@property(nonatomic,retain) FacebookLikeView *likeButton;
@property(nonatomic,retain) UIButton *checkInButton;
@property(nonatomic,retain) UILabel *storeName;
@property(nonatomic,retain) UILabel *storeAddress;
@property(nonatomic,retain) UILabel *subtitle;

@end

1 个答案:

答案 0 :(得分:0)

尝试[self addSubview: storeName]而不是[self.contentView addSubview:storeName]