2011-04-17 57 views
0

在我的cellForRowAtIndexPath方法中,我想動態創建一些按鈕並將它們放在單元格中彼此相鄰。我遇到的問題是sizeToFit方法總是把x座標置於0位置。有沒有辦法將位置偏移到前一個按鈕的旁邊?在TableView行中偏移UIButton框架

取而代之:Desired effect。我得到這個:Not desired

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 


UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"cell"]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
            reuseIdentifier:@"cell"] autorelease]; 
    cell.accessoryType = UITableViewCellAccessoryNone; 

    if ([indexPath section] == 0) { 
     UIButton *buttonClean = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     [buttonClean addTarget:self 
        action:@selector(aMethod:) 
     forControlEvents:UIControlEventTouchDown]; 
     [buttonClean setTitle:@"Clean Cup" forState:UIControlStateNormal]; 
     [buttonClean sizeToFit]; 
     [cell addSubview:buttonClean]; 

     UIButton *buttonAroma = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     [buttonAroma addTarget:self 
        action:@selector(aMethod:) 
     forControlEvents:UIControlEventTouchDown]; 
     [buttonAroma setTitle:@"Aroma" forState:UIControlStateNormal]; 
     [buttonAroma sizeToFit]; 
     [cell addSubview:buttonAroma]; 

回答

1

你應該設定自己的框架屬性定位UIViews。

這是一個選項:

[buttonAroma setFrame:CGRectMake(buttonClean.frame.size.width,0,buttonAroma.frame.size.width,buttonAroma.frame.size.height)]; 

你還應該添加您欣賞到細胞的內容查看,而不是將它們添加到直接的細胞:

[cell.contentView addSubview:buttonAroma]; 

見的UIView的框架物業在這裏:

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instp/UIView/frame

見的UITableViewCell的內容查看物業位置:

http://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html#//apple_ref/occ/instp/UITableViewCell/contentView

..那裏說:

如果要通過 簡單地增加額外的觀點來定製細胞,你 應該添加他們到內容視圖 他們將被適當定位 隨着細胞轉換進出 的編輯模式。

+0

工作完美。 – wiznaibus 2011-04-17 04:37:59

0

這不是sizeToFit方法,它把它們放在y = 0,這是事實,你從來沒有設置任何其他位置。您可以通過分配其centerframe屬性來移動每個按鈕;對於後者,您當然會想要讀出屬性,修改CGRect的來源,並將其設置回屬性中,以免弄亂大小。