我是新來的目標c,並嘗試學習創建一個用戶界面的基礎知識。在我的UIView類中,我創建了一個帶有按鈕的網格,但這些按鈕實際上並不存在(據我所知)。理想情況下,當我點擊一個按鈕時,圖像應該會改變,但這不會發生。我應該在哪裏解決問題?用按鈕填充網格
- (id)initWithFrame:(CGRect)frame {
if(self = [super init]){
tiles_ = [NSMutableArray array];
tileClosed = NO;
}
return self = [super initWithFrame:frame];
}
- (void) initTile : (Tile *) sender
{
int MINE_COUNT = 16;
for(int i = 0; i < MINE_COUNT; i++){
while(1){
int rand = random() % [tiles_ count];
Tile * tile = [tiles_ objectAtIndex:rand];
if(tile != sender && !tile.isMine){
tile.isMine = YES;
break;
}
}
}
tileClosed = YES;
}
- (void)drawRect:(CGRect)rect
{
NSLog(@"drawRect:");
CGContextRef context = UIGraphicsGetCurrentContext();
// shrink into upper left quadrant
CGRect bounds = [self bounds]; // get view's location and size
CGFloat w = CGRectGetWidth(bounds); // w = width of view (in points)
CGFloat h = CGRectGetHeight (bounds); // h = height of view (in points)
dw = w/16.0f; // dw = width of cell (in points)
dh = h/16.0f; // dh = height of cell (in points)
NSLog(@"view (width,height) = (%g,%g)", w, h);
NSLog(@"cell (width,height) = (%g,%g)", dw, dh);
// draw lines to form a 16x16 cell grid
CGContextBeginPath(context); // begin collecting drawing operations
for (int i = 1; i < 16; ++i)
{
// draw horizontal grid line
CGContextMoveToPoint(context, 0, i*dh);
CGContextAddLineToPoint(context, w, i*dh);
}
for (int i = 1; i < 16; ++i)
{
// draw vertical grid line
CGContextMoveToPoint(context, i*dw, 0);
CGContextAddLineToPoint(context, i*dw, h);
}
for(int x=1; x<16;x++){
for(int y=1;y<16;y++){
Tile * tile = [[Tile alloc] init];
[tile setFrame:CGRectMake(x * 16.0f, y * 16.0f, 16.0f, 16.0f)];
[tile addTarget:self action:@selector(clickCell:) forControlEvents:UIControlEventTouchUpInside];
[tiles_ addObject: tile]; }
}
[[UIColor grayColor] setStroke]; // use gray as stroke color
CGContextDrawPath(context, kCGPathStroke); // execute collected drawing ops
}
- (void) clickCell : (Tile *) sender
{
if(! tileClosed) [self initTile: sender];
[sender open];
}
此外,是否有任何簡單的指南/教程來學習UIView的基礎知識? – krikara 2013-03-04 01:06:40
Tile的定義是什麼? – occulus 2013-03-04 01:44:01
順便說一句,不要命名任何方法以'init'開頭,除非它實際上是一個init方法。你的initTile忽略了這一點,因此打破了Cocoa Touch命名約定。 – occulus 2013-03-04 01:44:37