Create a button in the iOS for loop. The width of the button is based on the text above.
Recently, you need to use a tab to create a demo.
The label size is adjusted based on the text above. The text is automatically wrapped according to the data returned by the background.
NSArray * arr = @ [@ ignorance, @ changeable, @ Shi Nai, @ alas, @ Simon blow snow, @ Haha, @, @, @ 一, @ Hua, @ big event, @ If You Are the One, @ hehah]; CGFloat w = 0; // Save the width of the previous button and the distance between the previous button and the edge of the screen CGFloat h = 200; // It is used to control the height of the button from the parent view (int I = 0; I <arr. count; I ++) {UIButton * button = [UIButton buttonWithType: UIButtonTypeSystem]; button. tag = 100 + I; button. backgroundColor = [UIColor greenColor]; [button addTarget: self action: @ selector (handleClick :) forControlEvents: UIControlEventTouchUpInside]; [button setTitleColor: [UIColor redColor] forState: UIControlStateNormal]; // calculate the text size NSDictionary * attributes =@{ NSFontAttributeName: [UIFont systemFontOfSize: 12]}; CGFloat length = [arr [I] boundingRectWithSize: CGSizeMake (320,200 0 options: NSStringDrawingUsesLineFragmentOrigin attributes: attributes context: nil]. size. width; // assign a value to the button [button setTitle: arr [I] forState: UIControlStateNormal]; // set the frame button of the button. frame = CGRectMake (10 + w, h, length + 15, 30 ); // when the button position exceeds the edge of the screen, the line feed 320 is only the width of the parent view of the button. if (10 + w + length + 15> 320) {w = 0; // set w to 0 h = h + button when changing rows. frame. size. height + 10; // The button is also changed from the parent view. frame = CGRectMake (10 + w, h, length + 15, 30); // reset the frame of the button} w = button. frame. size. width + button. frame. origin. x; [self. view addSubview: button];} Click Event-(void) handleClick :( UIButton *) btn {NSLog (@ % ld, btn. tag );}