这个问题很难解释。我试图在屏幕上创建一组 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/