通过从NSArray获取名称无法正确设置UIButton图像

时间:2015-02-05 04:05:18

标签: ios uibutton nsarray

您好我有这样的问题。在我的ViewController我有一个像这样的委托方法

`

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{

        imgArray=[NSArray arrayWithObjects:@"water-dark.png",@"land-dark.png",@"animal-dark.png",@"air-dark.png",@"other-dark.png", nil];
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, 50, 50);
    button.layer.cornerRadius=button.frame.size.width/2.0;
    button.layer.borderWidth=2;
    button.clipsToBounds = YES;


    button.titleLabel.font = [button.titleLabel.font fontWithSize:15];
    [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
  }

  //set button label
  [button setTitle:[NSString stringWithFormat:@"%i", index] forState:UIControlStateNormal];
  NSString *strIndex=[NSString stringWithFormat:@"%i",index];

  [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",      [imgArray objectAtIndex:[strIndex intValue]]]] forState:UIControlStateNormal];

  NSLog(@" CURRENT INDEX %i",index);

  return button;


}

`

这里我在viewcontroller. Those 5 buttons titles are setting perfectly. I put the index number as the title. And now I want to get the image name from the imgArray`上设置了5个按钮,并将每个图像设置为按钮。但问题是

仅设置第0个按钮图像和第4个(第5个)按钮图像。但是当我尝试通过从阵列中取出来打印图像名称时。全部打印在每个按钮上。

这应该是什么原因?我该如何解决这个问题呢。请帮帮我

这是我目前得到的输出。但是我需要用数组中的图像填充所有5个按钮。

enter image description here

1 个答案:

答案 0 :(得分:0)

嘿首先没有必要采取Button及其点击事件,你可以在此方法中返回- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view中的视图,因为我列出了beolw。 当然,你想要它的点击事件,你可以使用其中一个代表- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index

这是您的主要方法viewForItemAtIndex()

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view 
{
      view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 250, 250)];
      ((UIImageView *)view).image = [UIImage imageNamed:[imgArray objectAtIndex:index]];
      view.alpha = 1.0;
      [view.layer setCornerRadius:125];
      [((UIImageView *)view).layer setMasksToBounds:YES];
      [((UIImageView *)view) setContentMode:UIViewContentModeScaleAspectFit];
      view.contentMode = UIViewContentModeCenter;
      return view;
}

此处arrImages在视图控制器的.h文件中声明,并以viewDidLoad()方法分配,即imgArray = [NSArray arrayWithObjects:@"water-dark.png",@"land-dark.png",@"animal-dark.png",@"air-dark.png",@"other-dark.png", nil];

并且对于知识,没有必要在每个图像名称之后用.png编写或分配图像数组,就像你也可以写imgArray = [NSArray arrayWithObjects:@"water-dark",@"land-dark",@"animal-dark",@"air-dark",@"other-dark", nil];