oe a
oe a

Reputation: 2280

Adding button to cell

I have a subclass of UITableCell and here is my code so far:

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

        voteCount = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width/2, 10, 10, self.frame.size.height)];
        voteCount.text = @"24";
        [self.contentView addSubview:voteCount];         

        upVote = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width/3, 0, 20 , self.frame.size.height)];
        upVote.titleLabel.text = @"vote";
        [self.contentView addSubview:upVote];

    }
    return self;
}

The label shows up but the button does not. What am I doing wrong?

Upvotes: 0

Views: 76

Answers (2)

Anand Gautam
Anand Gautam

Reputation: 2579

use below code..

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

         //For UILabel
            voteCount = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width/2, 10, 10, self.frame.size.height)];
            voteCount.text = @"24";
            [self.contentView addSubview:voteCount]; 

        //For UIButton

        upVote = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [upVote addTarget:self 
           action:@selector(aMethod:)
        forControlEvents:UIControlEventTouchUpInside];
        [upVote setTitle:@"Title" forState:UIControlStateNormal];
        upVote.frame = CGRectMake(20.0, 10.0, 60.0, 60.0);//set your coordinates
        [self.contentView addSubview:upVote];

        }
        return self;
    }

It will work..

Upvotes: 2

Aaron Brager
Aaron Brager

Reputation: 66302

You need to use [UIButton +buttonWithType:].

You also need to use [UIButton -setTitle:forState:], not just set the text of its titleLabel.

Upvotes: 1

Related Questions