iphone - 根据存储在 NSArray 中特定索引处的图像以编程方式设置 UIButton 的图像

标签 iphone objective-c ios uibutton nsarray

这个问题很难解释。我试图在屏幕上创建一组 UIButtons,它基于 NSArray 中的条目数。我创建了一个包含许多图像的 NSArray,如下所示:

socialArray = [[NSArray alloc] initWithObjects:
                   [UIImage imageNamed:@"FacebookButton.png"],
                   [UIImage imageNamed:@"WebsiteSocialButton.png"],
                   [UIImage imageNamed:@"TumblrButton.png"],
                   [UIImage imageNamed:@"TwitterButton.png"],
                   [UIImage imageNamed:@"InstagramButton.png"],
                   [UIImage imageNamed:@"VimeoButton.png"],
                   [UIImage imageNamed:@"GooglePlusButton.png"],
                   [UIImage imageNamed:@"YouTubeButton.png"],
                   [UIImage imageNamed:@"PinterestButton.png"],
                  nil];

并基于此创建 View 中的项目数量,如下所示:

- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    return [socialArray count];
}

然后我以编程方式创建按钮并设置其图像,如下所示:

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{ 
    UIButton *button = (UIButton *)view;
    if (button == nil)
    {
        //no button available to recycle, so create new one
        UIImage *image = [UIImage imageNamed:@"page.png"];
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setBackgroundImage:image forState:UIControlStateNormal];
        button.titleLabel.font = [button.titleLabel.font fontWithSize:50];
        [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
    }

    //set button label
    [button setTitle:[socialArray objectAtIndex:0] forState:UIControlStateNormal];

    return button;
}

我真正想做的是根据数组中指定的图像设置按钮的图像。因此,第一个按钮获取索引 0 处指定的 PNG 文件,第二个按钮获取索引 1 处的图像,依此类推。

关于如何做到这一点有什么建议吗?

最佳答案

UIImage *image = [socialArray objectAtIndex:index];

(您必须在 if 语句之外执行此操作,否则不会为重复使用的按钮设置图像。)

关于iphone - 根据存储在 NSArray 中特定索引处的图像以编程方式设置 UIButton 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10552892/

相关文章:

ios - 按下 SFSafariViewController 时出现黑色标签栏

iphone - 在 iOS 中绘制矩形

IOS:如何使用代码验证用户的电话号码

iphone - iOS - UINavigationController 添加多个正确的项目?

objective-c - 如何在 Objective-C 中动态加载类?

objective-c - 处理由于 iOS 通讯录 API 中的链接卡导致的重复联系人

ios - 为什么我的库无法在 CocoaPods 网站上扩展?

ios - 如何在按下主页按钮后重置 ViewController 并返回到同一个 ViewController

iphone - 将对象的委托(delegate)设置为 nil,这些对象在 cellforrowatindexpath 中分配给 self

ios - 在 iPhone 上将 .caf 转换为 .mp3