ios - UIButton调整宽度为文本宽度

标签 ios uibutton

我有以下用于水平滚动菜单的代码。但文本看起来如下(示例):

我的屁股……号码

我有以下代码:

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;
}

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

最佳答案

你可以这样使用

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);

关于ios - UIButton调整宽度为文本宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23143555/

相关文章:

ios - UIButton 从 Core Data 增加一个数组,从另一个类完成

ios - 为什么我不能更改 UIButton 文本颜色?

ios - UIButton 背景图像调整大小

ios - iphone 应用程序 : put a toolbar on the top

ios - Xcode 事件监视器中奇怪的 CPU 使用率

iOS 如何限制 ASIHTTPRequest 并发连接数?

ios - 临时安装 ios 失败 | 0x243000 verify_signer_identity

javascript - 如何在 Safari 中打开外部链接而不是应用程序的 UIWebView?

ios - 将 UIButton 添加到 UITableView 的 detailTextLabel/右侧

ios - 如何使用 UIImage RenderingMode AlwaysTemplate 防止粗体图像