UIButton将宽度调整为文本宽度

时间:2014-04-17 21:13:26

标签: ios uibutton

我有以下代码用于水平滚动菜单。但文本如下(例子):

... mybutt棕土

我有以下代码:

scroll.contentSize = CGSizeMake(categoryArray.count * 100 + 100, 50);
scroll.showsHorizontalScrollIndicator = YES;
[scroll setBackgroundColor:[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.6]];

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(5,15,100,20); // position in the parent view and set the size of the button
[myButton setTitle:@"All" forState:UIControlStateNormal];
[myButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
// heb ik toegevoegd
[myButton.titleLabel setFont:[UIFont systemFontOfSize:18]];
/////////////
[myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
// add targets and actions
[myButton addTarget:self action:@selector(cmdCategroy:) forControlEvents:UIControlEventTouchUpInside];
[scroll addSubview:myButton];
myButton.tag = categoryArray.count + 1;


for (int y = 0; y < categoryArray.count; y++) {
    //NSLog(@"nb cat : %d",categoryArray.count);
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    myButton.frame = CGRectMake(100 + 5 + 100 * y,15,100,20); // position in the parent view and set the size of the button
    [myButton setTitle:[categoryArray objectAtIndex:y] forState:UIControlStateNormal];
    //[myButton sizeToFit];
    [myButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
    // heb ik toegevoegd
    [myButton.titleLabel setFont:[UIFont systemFontOfSize:18]];
    //stringsize.width
    /////////////
    [myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    // add targets and actions
    [myButton addTarget:self action:@selector(cmdCategroy:) forControlEvents:UIControlEventTouchUpInside];
    [scroll addSubview:myButton];
    myButton.tag = y;
}

如何使文本不被截断并将按钮宽度设置为文本的宽度?

2 个答案:

答案 0 :(得分:3)

你可以这样使用

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    NSString *str= @"your text";
    CGSize maximumSize = CGSizeMake(300, 9999);

    UIFont *myFont = [UIFont fontWithName:@"MyriadPro-Regular" size:12];

    CGSize myStringSize = [str sizeWithFont:myFont
                          constrainedToSize:maximumSize
                              lineBreakMode:NSLineBreakByWordWrapping];
    myButton.frame=cgrectmake(button.frame.origin.x,button.frame.origin.y,mystringsize.width,button.frame.size.height);

答案 1 :(得分:0)

基本上,计算字符串的大小宽度并将按钮框设置为该值。这是一个很好的简短方法。

    CGSize size = [myButton.titleLabel.text sizeWithAttributes:[NSDictionary dictionaryWithObject:label.titleLabel.font forKey:NSFontAttributeName]];
    myButton.frame = CGRectMake(myButton.frame.origin.x,myButton.frame.origin.y, ceil(size.width), myButton.frame.size.height);