简体   繁体   中英

How to create dynamic label and button on run time in iOS?

I have to create a label and button that always be centered align, user will select different item in any sequence and whenever user select an option it should be displayed in a line with a label and a cross button. when user will tap on cross button then that option will be deselected and remaining labels and buttons will set their position in center.

You may get a good idea with the following image 在此处输入图片说明

在此处输入图片说明在此处输入图片说明 see "Hers" with a "X" button. here all the selected options will come

kindly guide me

Because I'm just that cool a person, I decided to devote some time on this issue for you :)

Download an example from my Dropbox: http://dl.dropbox.com/u/6487838/FSButtonLabelTest.zip

I'll explain the code a bit here later today.

Edit: Added some animations.

Adding a lable

UILabel *myLabel  =  [[UILabel alloc]init];
myLabel.frame     =  CGRectMake(50,100,100,20);
myLabel.text      =  @"Your_Text";
[self.view addSubview:myLabel];

Adding a custom button with image

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame     =  CGRectMake(210, 100, 20, 20);
[myButton setImage:[UIImage imageNamed:@"cross.png"] forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(removeFunction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myButton];

replace the removeFunction in the button target wiht your function.. If you are not sure of the coordinates of the button or label then first go into IB and place a button where you want it to be and then in the right side check the coordinates of button in show the size inspector and use those coordinates in your code this will give you a fair idea about where your button will go after you add it programmatically... hope this will help you

   UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    UIButton *btn =[[UIButton alloc]initWithFrame:CGRectMake(50,50,200,200)];
    [self.view addSubview:btn];
    [self.view addSubview:label];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM