码迷,mamicode.com
首页 > 其他好文 > 详细

九宫格

时间:2015-03-20 15:50:07      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

-(void)viewDidLoad{

  //列数

  int columns = 3;

  //每个图片之间的间距 = (控制器view的宽度 - 列数 * 图片的宽度)/ (列数 + 1)

  CGFloat margin = (self.view.frame.size.width - columns * kImgW) / (columns + 1);

  //第一张图片的Y值

  CGFliat oneY = 100;

  //第一涨图片的X值

  CGFloat oneX = margin;

  for (int i=0; i<9; i++) {

    NSString *imgName = [NSString stringWithFormat:@"01%d.png",i];

    // i这个位置对应的列数

    int col = i % columns;

    // i 这个位置对应的行数

    int row = i / columns;

    // 列数(col)决定了x

    CGFloat x = oneX + col * (kImgW * margin);

    // 行数(row)决定了y

    CGFloat y = oneY + row * (kImgW + margin);

    [self addImg: imgName x: x y: y];

  }

}

- (void)addImg:(NSString *)icon x:(CGFloat)x y:(CGFloat)y{

  UIImageView *imageView = [[UIImageView alloc] init];

  imageView.image = [UIImage imageNamed:icon];

  imageView.frame = CGRectMake(x, y, 40, 40);

  [self.view addSubview: imageView];

}

#param mark 更改图片的列数

- (void)indexChange:(UISegmentedControl *)sender {

  //动画

  [UIView beginAnimations:nil context:nil];

  [UIView setAnimationDuration:0.5];

  //sender.selectedSegmentIndex 

  int columns = sender.selectedSegmentIndex + 2;

  CGFloat margin = (self.view.frame.size.width - columns * kImgW) / (columns + 1);

  CGFliat oneY = 100;

  CGFloat oneX = margin;

  for (int i=0; i<9; i++) {

  int col = i % columns;

  int row = i / columns;

  CGFloat x = oneX + col * (kImgW * margin);

  CGFloat y = oneY + row * (kImgW + margin);

  //取出i + 1 位置对应的imageView,设置x,y值

  //+ 1 是为了跳过最前面的UISegmentControl

  UIView *child = self.view.subviews[i + 1];

  //取出frame

  CGRect tempF = child.frame;

  //修改x,y

  // tempF.origin.x = x;

  // tempF.origin.y = y;

  tempF.origin = CGPointMake(x, y);

  //重新赋值

  child.frame = tempF;

  }

  [UIView commitAnimations];

}

九宫格

标签:

原文地址:http://www.cnblogs.com/yedandan/p/4353619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!