我以编程方式创建了 10 个按钮,并在按钮中设置了标题。现在我想动态增加按钮框架大小,它取决于文本。
我给出了一些条件并设置了框架大小。但我如何设置确切的帧大小取决于文本(动态获取文本)。
我的示例代码是,
float x=0, y=0, w, h=20;
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
if([titleString length] <= 5)
{
w = 50;
btn.frame = CGRectMake(x,y,w,h);
x = x + 70;
}
if (([titleString length] >= 6) && ([titleString length] <=10))
{
w = 70;
btn.frame = CGRectMake(x,y,w,h);
x = x + 90;
}
if(([titleString length] >= 11) && ([titleString length] <=15))
{
w = 105;
btn.frame = CGRectMake(x,y,w,h);
x = x + 120;
}
if([titleString length] >= 16)
{
w = 120;
btn.frame = CGRectMake(x,y,w,h);
x = x + 140;
}
[btn setTitle:titleString forState: UIControlStateNormal];
[btn setTag:i];
[self.view addSubview:btn];
}
请参阅示例图像,
图片2 http://www.freeimagehosting.net/uploads/b6e0f234dc.png http://www.freeimagehosting.net/uploads/b6e0f234dc.png
图片 1 http://www.freeimagehosting.net/uploads/6b3daab12f.png http://www.freeimagehosting.net/uploads/6b3daab12f.png
那么,是否可以根据文本设置确切的按钮框架大小?请指导我。
Thanks