0

我是目标 c 的新手,并尝试学习创建 UI 的基础知识。在我的 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];
}
4

2 回答 2

0

您的 init 方法不正确,您可以简单地将其更改为

    - (id)initWithFrame:(CGRect)frame 
      {
        self = [super initWithFrame:frame]
        if( self)
        {
          tiles_ = [NSMutableArray array];
          tileClosed = NO;
        }
        return self;
      }

并且对于要出现的按钮,您没有将其添加到子视图中

    [self.view addSubview:tile]; 

不见了。

于 2013-03-04T14:19:15.740 回答
0

你的initwithFrame:方法坏了:返回线应该是return self;.

你现在所做的实际上破坏了tiles_数组,所以它最终为零,因此试图在其中存储图块什么都不做(因此它们不会被保留)。

于 2013-03-04T01:49:04.733 回答