我有以下用于水平滚动菜单的代码。但文本看起来如下(示例):
我的屁股……号码
我有以下代码:
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/