Mishal Awan
Mishal Awan

Reputation: 724

How to add UIbuttons on UIview programatically

I have created a view programatically, and want to add 2 button on that view but while running app view, buttons on it are not presented. Here is my sample code, seems problem is with frame but how to adjust button frames according to the frame of view:

cv = [[UIView alloc]initWithFrame:CGRectMake(200, 60, 100, 80)];

UIButton *label1 = [[UIButton alloc]initWithFrame:CGRectMake(100,90, 200, 30)]; 
label1=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[label1 setTitle: @"Mark as unread" forState: UIControlStateNormal]; 
label1.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0]; 
[label1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
label1.backgroundColor=[UIColor blackColor]; 

[cv addSubview:label1]; 

UIButton *label2 = [[UIButton alloc]initWithFrame:CGRectMake(-50,20, 200, 30)]; 
[label2 setTitle: @"Mark as read" forState: UIControlStateNormal]; 
label2=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
label2.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0]; 
[label2 addTarget:self action:@selector(nonbuttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

[cv addSubview:label2];

Upvotes: 0

Views: 74

Answers (1)

Mrunal
Mrunal

Reputation: 14118

First try this code, I have simply removed buttontype setting lines.

UIButton *label1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 30)]; 
//label1=[UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton *label2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 40, 100, 30)];
//label2=[UIButton buttonWithType:UIButtonTypeRoundedRect];

Reason: label1 is getting created as per your frame in first line, and in next line, label1 is getting re-assigned to a new button instance created by buttonWithType method. Hence it was getting overridden over first instance where you have already set frames.

Hence your code will become like this:

cv = [[UIView alloc]initWithFrame:CGRectMake(200, 60, 100, 80)];

UIButton *label1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 30)]; 
[label1 setTitle: @"Mark as unread" forState: UIControlStateNormal]; 
label1.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0]; 
[label1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
label1.backgroundColor=[UIColor blackColor]; 

[cv addSubview:label1]; 

UIButton *label2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 40, 100, 30)]; 
[label2 setTitle: @"Mark as read" forState: UIControlStateNormal]; 
label2.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0]; 
[label2 addTarget:self action:@selector(nonbuttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

[cv addSubview:label2];

Upvotes: 1

Related Questions