How can i increase the button width dynamically depends on the text size in iphone?

后端 未结 4 1045
一生所求
一生所求 2021-02-06 15:12

I have created 10 buttons programmatically and set the titles in the button. Now i want to increase the button frame size dynamically,its depends on the text.

I given so

4条回答
  •  独厮守ぢ
    2021-02-06 15:46

    I got the answer and my working code is,

            float x=0;
    
            for(int i = 100; i < 110; i++)
             {
                 btn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
    
                 UIImage * img = [UIImage imageNamed:@"Round_Rect4.png"];
    
                [btn setBackgroundImage:img forState:UIControlStateSelected];
    
                titleString = [titleArray objectAtIndex:i-100];  // get button title
    
               CGSize fontSize = [titleString sizeWithFont:[UIFont systemFontOfSize:12.0]];
    
                CGRect currentFrame = btn.frame;
    
                CGRect buttonFrame = CGRectMake(x, currentFrame.origin.y, fontSize.width + 22.0, fontSize.height + 12.0);
    
               [btn setFrame:buttonFrame];
    
                x = x + fontSize.width + 35.0;
    
                [btn setTitle:titleString forState: UIControlStateNormal];
    
                [btn setTag:i];
    
                [self.view addSubview:btn];
    
    }
    

提交回复
热议问题