一定要記得,addSubview 一定要在 parentView 「出現」( willAppear, didAppear ) 的時候,去執行 parentView 的 addSubview 才是正確的!否則會出現 subview 新增至錯誤位子的問題。
例如,要客製化新增一個「價格」的 subview 至 UITableViewCell 的 contentView 之「右下角」裡 :
//Code
static NSInteger kCellPriceViewTag = 799;
//一般都是在這方法裡設定 Cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{}
//而 Custom 的 UIView 內容則建議在這裡設定
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if( cell ){
//新增客製化的價格
NSDictionary *infos = [self.datasobjectAtIndex:indexPath.row];
if( [infos count] > 0 ){
for( UIView *subview in _targetCell.contentView.subviews ){
if( subview.tag == kCellPriceViewTag ){
[subview removeFromSuperview];
}
}
CGFloat _moneyWidth = 110.0f;
CGFloat _moneyHeight = 25.0f;
CGFloat _coinWidth = 50.0f;
CGFloat _coinHeight = 25.0f;
CGFloat _width = _moneyWidth + _coinWidth;
CGFloat _height = 30.0f;
CGRect _cellFrame = _targetCell.frame;
UIView *_priceView = [[UIViewalloc] initWithFrame:CGRectMake(_cellFrame.size.width - _width,
_cellFrame.size.height - _height,
_width,
_height)];
[_priceView setTag:kCellPriceViewTag];
//
UILabel *_moneyLabel = [[UILabelalloc] initWithFrame:CGRectMake(0.0f, 0.0f, _moneyWidth, _moneyHeight)];
[_moneyLabel setText:[NSString stringWithFormat:@"$%@", @"2,990"]];
[_moneyLabel setBackgroundColor:[UIColor clearColor]];
[_moneyLabel setTextColor:[UIColor blackColor]];
[_moneyLabel setFont:[UIFontfontWithName:@"Futura" size:14.0f]];
[_moneyLabel setTextAlignment:NSTextAlignmentRight];
[_priceView addSubview:_moneyLabel];
[_moneyLabel release];
//
UILabel *_coinLabel = [[UILabelalloc] initWithFrame:CGRectMake(_moneyWidth, 0.0f, _coinWidth, _coinHeight)];
[_coinLabel setText:[NSStringstringWithFormat:@" / %@", @"TWD"]];
[_coinLabel setBackgroundColor:[UIColor clearColor]];
[_coinLabel setTextColor:[UIColor colorWithRed:150.0/255.0 green:150.0/255.0 blue:150.0/255.0 alpha:1.0]];
[_coinLabel setFont:[UIFontsystemFontOfSize:9.0f]];
[_coinLabel setTextAlignment:NSTextAlignmentLeft];
[_priceView addSubview:_coinLabel];
[_coinLabel release];
//
[_targetCell.contentView addSubview:_priceView];
[_priceView release];
}
}
}