2012-04-13 27 views
0

截至目前,我的view.m文件中有一個for循環,在drawRect方法中。我有for循環在x軸上顯示圖像。我想要做的是能夠不僅在X軸上而且在Y軸上製作一個網格圖像。換句話說,你的典型網格。我還想讓網格中的每一個重複圖像都帶有一些附着在它上面的屬性,比如一個bool,一個我可以在觸摸時檢索它的id,以及它的座標。我會如何在objective-c中做這件事?這是我迄今爲止,這並不多:如何在UIView子類中創建對象的網格?

- (void)drawRect:(CGRect)rect 
{ 
    int intX = 0; 
    int intCounter = 0; 
    int intY = 0; 
    for (intCounter = 0; intCounter < 10; intCounter++) { 
     UIImage* pngLeaf = [UIImage imageNamed:@"leaf2.png"]; 
     CGRect imgRectDefault = CGRectMake(intX, 0, 34, 34); 
     [pngLeaf drawInRect:imgRectDefault]; 
     intX += 32; 
     intY += 32; 
    } 
} 
+0

即使你剛剛開始了,我可能會建議你在UIScrollView中使用UIImageView而不是UIView子類。從長遠來看,它會讓你的生活更輕鬆,並且你可以在你的UIImageView子類中放置你想要的任何屬性。 – 2012-04-13 01:03:21

+0

@Jay我剛剛讀了UIScrollView類的參考,並挑釁聽起來像一個好主意。儘管如此,我仍然陷在了漏洞之中。我想我需要的是一個對象數組,包括UIImage視圖。我只是不確定如何使用多維數組來創建網格。 – Scott 2012-04-13 01:27:43

回答

1

你會有一個更容易與UIViews的時間。

這裏是一個網格例程 - 它可以寫得更加緊湊,但它更容易理解大量顯式聲明的變量。把它放在你的主ViewController中,並在ViewWillAppear中調用它。

- (void)makeGrid 
{ 


int xStart = 0; 
int yStart = 0; 
int xCurrent = xStart; 
int yCurrent = yStart; 

UIImage * myImage = [UIImage imageNamed:@"juicy-tomato_small.png"]; 

int xStepSize = myImage.size.width; 
int yStepSize = myImage.size.height; 

int xCnt = 8; 
int yCnt = 8; 

int cellCounter = 0; 

UIView * gridContainerView = [[UIView alloc] init]; 
[self.view addSubview:gridContainerView]; 

for (int y = 0; y < yCnt; y++) { 
    for (int x = 0; x < xCnt; x++) { 
     printf("xCurrent %d yCurrent %d \n", xCurrent, yCurrent); 

     UIImageView * myView = [[UIImageView alloc] initWithImage:myImage]; 
     CGRect rect = myView.frame; 
     rect.origin.x = xCurrent; 
     rect.origin.y = yCurrent; 
     myView.frame = rect; 
     myView.tag = cellCounter; 
     [gridContainerView addSubview:myView]; 

     // just label stuff 
     UILabel * myLabel = [[UILabel alloc] init]; 
     myLabel.textColor = [UIColor blackColor]; 
     myLabel.textAlignment = UITextAlignmentCenter; 
     myLabel.frame = rect; 
     myLabel.backgroundColor = [UIColor clearColor]; 
     myLabel.text = [NSString stringWithFormat:@"%d",cellCounter]; 
     [gridContainerView addSubview:myLabel]; 
     //-------------------------------- 

     xCurrent += xStepSize; 
     cellCounter++; 
    } 

    xCurrent = xStart; 
    yCurrent += yStepSize; 
} 

CGRect repositionRect = gridContainerView.frame; 
repositionRect.origin.y = 100; 
gridContainerView.frame = repositionRect; 

} 
+0

@Jay一切都很好。我唯一需要改變的地方是你有xCurrent = xCurrent的地方。我只是將其更改爲xCurrent = xStart。 – Scott 2012-04-13 04:04:22

+0

解決了這個問題。玩的開心! – 2012-04-13 04:12:24