2011-04-17 60 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的来源,并将其设置回属性中,以免弄乱大小。