2012年3月16日金曜日

UITableViewのセクションのフッターを左寄せにする方法


UITableViewのSectionのフッターのアライメントはセンタリングのみで、左寄せにする場合はひと手間必要になります。

フッターにUIView(のサブクラス)をセットすることができるので、UILabelのインスタンスをセットします。

左寄せだけであればUILabelそのものでも実現できますが、左マージンやフォントサイズを変更する場合はサブクラスを作り、drawTextInRect(またはtextRectForBounds?)をオーバライドします。

@interface MyTableFotterLabel : UILabel
- (id)initWithFrame:(CGRect)frame;
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines;
@end

@implementation MyTableFotterLabel

//インスタンスの初期化。全セクション共通の属性を設定する。
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {   
        //左寄せ
        self.textAlignment = UITextAlignmentLeft;
        //背景を透明に設定。
        self.backgroundColor = [UIColor clearColor];
//好みでinsetを設定。
        self.shadowColor = [UIColor whiteColor];
        self.shadowOffset = CGSizeMake(1.0f, 1.0f);
        //フォントサイズ設定。
        self.font = [UIFont fontWithName:self.font.fontName size:14.0f];
    }
    return self;
}

//drawTextInRectをオーバライドし表示位置を設定。左右マージンを設定している。
- (void)drawTextInRect:(CGRect)rect
{
    rect.origin.x += 24.0f;
    rect.size.width -= 48.0f;
    [super drawTextInRect:rect];
}

//Referenceでは呼ばれることになっているが、5.0では呼ばれなかった。
//バージョン違いで呼ばれるかもしれないので実装しておいたほうが良いでしょう。
- (CGRect)textRectForBounds:(CGRect)bounds
        limitedToNumberOfLines:(NSInteger)numberOfLines
{
    bounds.origin.x += 24.0f;
    bounds.size.width -= 48.0f;
    return bounds;
}
@end

UITableViewオブジェクトのdelegate(デフォルトのままであればUITabelViewControllerオブジェクト)のtableView:viewForFooterInSection:をオーバライドし

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    //サイズをセットしてもUITableViewがセットし直すのでCGRectZeroでよい。
    UILabel * footer = [[IDTableFotterLabel alloc] initWithFrame:CGRectZero];
footer.text = @"セクション別のfooterテキスト";
    return footer;
}

//フッターの高さを返す。
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    //セクションのフォントサイズ、行数に応じて必要な適切な高さを返す。
    return 20.0f;
}

0 件のコメント: