2011-12-04 40 views

回答

16

您需要繼承UITableViewCell和覆蓋layoutSubviews方法:

- (void)layoutSubviews { 
    [super layoutSubviews]; 
    CGRect tmpFrame = self.imageView.frame; 
    tmpFrame.origin.x += 10; 
    self.imageView.frame = tmpFrame; 

    tmpFrame = self.textLabel.frame; 
    tmpFrame.origin.x += 10; 
    self.textLabel.frame = tmpFrame; 

    tmpFrame = self.detailTextLabel.frame; 
    tmpFrame.origin.x += 10; 
    self.detailTextLabel.frame = tmpFrame; 
} 
+1

這是一個非常簡單和容易的解決方案,您需要使用此代碼創建新的'UITableViewCell'子類,並更改您的'tableView:cellForRowAtIndexPath:'來分配您的子類別單元而不是常規的'UITableViewCell'。 –

2

讓UITableViewCell比內容開始更高更有意義嗎?如果你的內容始終是100像素高,只是使細胞110px得到你需要額外的空間10px的,沒有自定義單元格需要:)

+0

我想要左邊距是額外的10px – JAHelia

+0

好吧,這不是一個HTML頁面,你有320像素的有限空間,所以你只需要確保你只使用最右邊的310像素,所以左邊的10像素是免費的,並被用作「間距」。 –

+0

是的,我知道這一點,但如何設置單元格的左邊距? – JAHelia

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

此方法將返回該單元格,你可以在它配置電池。只需設置控件的框架,將它們移動到計算位置即可。

+0

你可以發佈一個代碼片段,展示如何增加此方法中單元格的左邊距(或填充左等效)嗎? – JAHelia

1

要設置左邊距可以使用:

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:  (NSIndexPath *)indexPath 
{ 
    return 1; 
} 
+2

這不會設置邊距,它會設置指定行的深度,以在該部分中顯示其分層位置。 – Daniel

+0

該解決方案非常巧妙,但如果您想要不幸地減少默認邊距,則無法使用... – turingtested

1

安德烈有一個很好的解決方案,但如果你使用附屬視圖你需要這樣的代碼:

const int MARGIN = 16; // Left and right margin 

- (void)layoutSubviews { 
    [super layoutSubviews]; 

    /* Add left margin to the image and both labels */ 
    CGRect frame = self.imageView.frame; 
    frame.origin.x += MARGIN; 
    self.imageView.frame = frame; 

    frame = self.textLabel.frame; 
    frame.origin.x += MARGIN; 
    frame.size.width -= 2 * MARGIN; 
    self.textLabel.frame = frame; 

    frame = self.detailTextLabel.frame; 
    frame.origin.x += MARGIN; 
    frame.size.width -= 2 * MARGIN; 
    self.detailTextLabel.frame = frame; 

    /* Add right margin to the accesory view */ 
    if (self.accessoryType != UITableViewCellAccessoryNone) { 
     float estimatedAccesoryX = MAX(self.textLabel.frame.origin.x + self.textLabel.frame.size.width, self.detailTextLabel.frame.origin.x + self.detailTextLabel.frame.size.width); 

     for (UIView *subview in self.subviews) { 
      if (subview != self.textLabel && 
       subview != self.detailTextLabel && 
       subview != self.backgroundView && 
       subview != self.contentView && 
       subview != self.selectedBackgroundView && 
       subview != self.imageView && 
       subview.frame.origin.x > estimatedAccesoryX) { 

       // This subview should be the accessory, change its frame 
       frame = subview.frame; 
       frame.origin.x -= MARGIN; 
       subview.frame = frame; 
       break; 
      } 
     } 
    } 
} 

有沒有簡單的WA y處理輔助視圖。 我一直在尋找一段時間,這是迄今爲止我所見過的最好的解決方案。

相關問題