2012-02-10 14 views

答えて

1

ここでは、GridViewを非常に単純化して実装しています。必要に応じてカスタマイズする必要があるかもしれませんが、良いスタートになるかもしれません。 initWithFrame:という名前で作成し、UIViewオブジェクトをchildren配列に追加します。回転後にsetNeedsLayoutを呼び出す必要があるかもしれませんが、覚えていないかもしれません。

// 
// GridView.h 
// Project 
// 
// Created by Anthony Picciano on 7/28/10. 
// 

#import <UIKit/UIKit.h> 

#define GRID_VIEW_DEFAULT_COLUMNS 1 
#define GRID_VIEW_DEFAULT_HGAP 10.0f 
#define GRID_VIEW_DEFAULT_VGAP 10.0f 
#define GRID_VIEW_LAYOUT_NOTIFICATION @"layoutNotification" 


@interface GridView : UIView { 
    int columns; 
    float hgap; 
    float vgap; 
} 

@property (nonatomic) int columns; 
@property (nonatomic) float hgap; 
@property (nonatomic) float vgap; 

@end 


// 
// GridView.m 
// Project 
// 
// Created by Anthony Picciano on 7/28/10. 
// 

#import "GridView.h" 


@implementation GridView 
@synthesize columns, hgap, vgap; 


- (id)initWithFrame:(CGRect)frame { 
    if ((self = [super initWithFrame:frame])) { 
     columns = GRID_VIEW_DEFAULT_COLUMNS; 
     hgap = GRID_VIEW_DEFAULT_HGAP; 
     vgap = GRID_VIEW_DEFAULT_VGAP; 
    } 
    return self; 
} 

- (void)layoutSubviews { 
    float xpos = 0; 
    float ypos = 0; 
    float width = self.frame.size.width; 
    float cellWidth = (width - (hgap * (columns - 1)))/columns; 

    int currentColumn = 1; // columns number start at 1, not 0 
    float maxRowHeight = 0.0f; 

    for (UIView *child in self.subviews) { 
     CGRect childFrame = CGRectMake(xpos, ypos, cellWidth, child.frame.size.height); 
     child.frame = childFrame; 

     if (child.frame.size.height > maxRowHeight) { 
      maxRowHeight = child.frame.size.height; 
     } 

     if (currentColumn < columns) { 
      currentColumn++; 
      xpos += cellWidth + hgap; 
     } else { 
      currentColumn = 1; 
      xpos = 0.0f; 
      ypos += maxRowHeight + vgap; 
      maxRowHeight = 0.0f; 
     } 
    } 

    if (currentColumn == 1) { 
     ypos -= vgap; 
    } else { 
     ypos += maxRowHeight; 
    } 

    CGRect aFrame = self.frame; 
    aFrame.size = CGSizeMake(width, ypos); 
    self.frame = aFrame;  

    NSNotification *notification = [NSNotification notificationWithName:GRID_VIEW_LAYOUT_NOTIFICATION object:nil]; 
    [[NSNotificationCenter defaultCenter] postNotification:notification]; 
} 

- (void)dealloc { 
    [super dealloc]; 
} 


@end 
関連する問題