2016-07-25 43 views
1

UITableViewCell包含的唯一東西是一個UIButton。到目前爲止,我可以在控制檯上打印被點擊的UIButton的'currentTitle'。我想要做的是改變點擊按鈕的風格粗體。如果再點擊一個,前者應該回到正常狀態,而新的需要改變爲粗體。在UITableViewCell中,如何將單擊按鈕的樣式更改爲粗體,而其他單元保持不變?

它們是UIViewController中的多個按鈕,我可以通過單獨添加這些按鈕來輕鬆完成此操作,但我不認爲這種情況會以這種方式完成。

我應該保存UIViewController類中所選按鈕的索引,並重新加載UITableView?如果是這樣,任何人都可以讓我知道如何處理這個?我有這個想法,但我不知道該怎麼做。

回答

3
var selectIndex:NSIndexPath = NSIndexPath(forRow: -1, inSection: 0) 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 
    let cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell 
    cell.btn.addTarget(self, action: Selector("ButtonAction:"), forControlEvents: UIControlEvents.TouchUpInside) 
    cell.btn.tag = indexPath.row 
    cell.btn.titleLabel?.font = UIFont.systemFontOfSize(20) 

    if indexPath.row == selectIndex.row 
    { 
     cell.btn.titleLabel?.font = UIFont.boldSystemFontOfSize(20) 
    } 
    return cell 
} 

func ButtonAction(sender: UIButton) 
{ 
    selectIndex = NSIndexPath(forRow: sender.tag, inSection: 0) 
    yourTableView.reloadData() 
} 
-1

你必須這樣做cellForRowAtIndexPath保持國旗說它已被選中。

此外,您必須在tableView.visibleCells上調用cellForRowAtIndexPath以選擇按鈕時,因爲cellForRowAtIndexPath僅在單元格進入視圖時才起作用。

+0

你不應該直接調用表視圖的數據源方法 – Paulw11

+0

@ Paulw11那麼上述問題的解決方案是什麼? – vinbhai4u

+0

通過要求表視圖使用'reloadCellsAtIndexPaths'或'reloadData'重新加載受影響的單元格,隱式調用它 – Paulw11

0

試試這個代碼

CustomTableViewCell.h

@property (nonatomic, weak) IBOutlet UIButton *button; 
@property (nonatomic, copy) void (^ButtonTapAction)(CustomTableViewCell *aCell); 

CustomTableViewCell.m

//Method assign to that button 
- (IBAction)arrowButtonTapped:(id)sender 
{ 
    if (self.ButtonTapAction) { 
     self.ButtonTapAction(self); 
    } 
} 

細胞用於tableview中的cellForRowAtIndexPath:

__weak typeof(self) weakSelf = self; 
     cell.arrowButtonTapAction = ^(CustomTableViewCell *aCell){ 
      aCell.button.titleLabel.font=[UIFont boldSystemFontOfSize:20]; 
     }; 

通過這種合作你不需要重新加載單元格。

0

您可以添加一個屬性,該屬性存儲與當前所選按鈕相對應的單元格的行。

在你的cellForRowAtIndexPath你檢查是否indexPath.row == selectedRow並設置適當的按鈕外觀。

當選擇更改時,請使用新選擇的行和先前選擇的行(如果適用)呼叫reloadCellsAtIndexPaths

相關問題