0

我有一个UIView并且我想添加一系列以编程方式生成UIButtons的。

我创建了一个方法,通过CGPoint.

我想将这些按钮连续放置 3 个,根据需要放置在尽可能多的行上。

我不知道如何以编程方式生成 x 和 y 坐标以将项目放置在视图上。一旦放置了三个按钮,我就被困在如何让按钮放到新行上。

这是我的代码,我想在此方法中处理某些内容以仅根据按钮的索引返回坐标:

- (CGPoint)calculateCoordinatesWithIndex:(NSInteger)index{
    NSInteger x = 100;
    NSInteger y = 50;
    return CGPointMake(x, y);
}

我能想到的唯一解决方案似乎非常笨拙且效率低下。

4

3 回答 3

2

你好怎么样:

#define BUTTON_WIDTH    100
#define BUTTON_HEIGHT   50
- (void) placeButtonsFromButtonsArray:(NSArray *) buttons{

   CGFloat currentXPosition = 0.0;
   CGFloat currentYPosition = 0.0;

   for (NSUInteger i = 0; i < [buttons count]; i++){
        b.frame = CGRectMake(currentXPosition, currentYPosition, BUTTON_WIDTH, BUTTON_HEIGHT);
        if (i%3 == 2){
           currentXPosition = 0;
           currentYPostion += BUTTON_HEIGHT;
        }
        else currentXPosition += BUTTON_WIDTH;
   }
}

or Using your method :

  - (CGPoint)calculateCoordinatesWithIndex:(NSInteger)index{

     //computes on which line the button should be
     NSUInteger line = (index/3);

     //computes on which row the button should be 
     NSUInteger row = (index%3) ;     

     return CGPointMake(row*BUTTON_WIDTH, line*BUTTON_HEIGHT);
}
于 2012-12-21T12:18:29.993 回答
1

If you're targeting iOS 6, you could use a UICollectionView for this.

于 2012-12-21T12:33:57.207 回答
0

试试这个,在.h

  {

NSInteger x;

 NSInteger y;

 int noOfbtninrow;

 }

  -(void)viewDidload

{


x = 100;

y = 50;

 noOfbtninrow=0;
 }

- (CGPoint)calculateCoordinatesWithIndex:(NSInteger)index
 {
   if(noOfbtninrow==3)

 {
  x=100;
   y=y+100
 noOfbtninrow=0;
  }

  else

 {
  noOfbtninrow++;
   x=x+100;
  }
  return CGPointMake(x, y);
  }
于 2012-12-21T12:17:58.150 回答