0

我现在正在制作一个应用程序的原型。我以编程方式向导航栏添加了一堆栏按钮:

NSArray *buttonTitles = [[NSArray alloc] initWithObjects:@"Alerts", @"Causes", @"Msgs", @"My Work", @"My Posts", nil];

NSMutableArray *rightBarButtons = [[NSMutableArray alloc] init];
for (int i = 0; i < 5; i++)
{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    rightButton.frame = CGRectMake(0, 0, 44, 34);
    [rightButton setTitle:[buttonTitles objectAtIndex:i] forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:10];
    rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [rightBarButtons addObject:rightItem];   
}

现在,它们看起来真的很难看,尤其是在导航栏上。我想拍摄一些图像(类似于标签栏图像)并将它们放在那里以替换按钮。我该怎么做?

对不起我的愚蠢,我是新手。

谢谢!

4

1 回答 1

0
 [rightButton setBackgroundImage:@"image.png" forState:UIControlStateNormal];

如果我正确理解你的问题,就会成功。

for (int i = 0; i < 5; i++)
{
    NSString* imageName = [NSString stringWithFormat:@"image-%d", i];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    rightButton.frame = CGRectMake(0, 0, 44, 34);
    [rightButton setTitle:[buttonTitles objectAtIndex:i] forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:10];
    [rightButton setBackgroundImage:imageName forState:UIControlStateNormal];
    rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [rightBarButtons addObject:rightItem];   
}

好吧,这就是我们可以做到的。我创建了一个 NSString (imageName),为字符串分配了 image-%d 的值,这意味着它将采用image-1何时i为 1 和image-2何时i为 2 的名称。

然后在这[rightButton setBackgroundImage:imageName forState:UIControlStateNormal];部分它只需要我们创建的字符串的名称(imageName)。

这意味着由于您的循环,您的图像应该被image-0命名image-5

如果您需要我澄清任何事情,我很乐意解释更多。

于 2012-06-08T17:33:04.323 回答