簡體   English   中英

無法更新自定義UITableViewCell中的子視圖

[英]Unable to update the Subview in a Custom UITableViewCell

我有一個自定義UITableViewCell ,其中有兩個UIViews 我想更改BackgroundColor半徑和UIViews更多屬性。

但是我做不到。

這是我的設置。

第1步:

Create A Custom Cell with XIB.

步驟2:在XIBCustomCell輸入Cell Identifer名稱。

步驟3:在viewDidLoad實例化NIB

 UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
 [[self mTableView] registerNib:nib forCellReuseIdentifier:@"CustomCell"];

步驟4:單元格在索引方法行:

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
    // Create an instance of ItemCell
   CustomCell *cell =  [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];

   [cell updateCellView];

   return cell;
}

步驟5:檢查兩次,出口連接均正常。

步驟6:自訂儲存格類別:

    #import "TransportCell.h"

    @implementation TransportCell

    - (void)awakeFromNib {
         // Initialization code

      }

    - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
       [super setSelected:selected animated:animated];

        // Configure the view for the selected state
     }


    - (void)updateCellView
    {
     self.backgroundView.backgroundColor = [UIColor redColor];
    }

   @end

此代碼對我的“單元格視圖”無效。

我調試代碼。 當我登錄backgroundView時, updateCellView方法時得到nil

在此輸入圖像描述

這是我的CustomCell的Xib:

在此輸入圖像描述

我必須更改內部UIView的屬性。(藍色)

而不是在cellForRowAtIndexPath中調用該方法,請嘗試以下操作:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
    // Create an instance of ItemCell
   CustomCell *cell =  [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
   return cell;
}

然后在您的自定義方法中

- (void)updateCellView
    {
     self.backgroundView.backgroundColor = [UIColor redColor];

     // reload the table view
     [self.tableView reloadData];
    }

您需要在方法更新單元格視圖中添加[tableview reloadData]

理想情況下,渲染單元所需的所有信息都應來自數據源或其他事件。 例如,如果您要更改邊框顏色,則應表示某個實體(例如用戶)執行了一個事件,或者數據源中的某些內容發生了變化,例如值已超過其閾值。

數據源中的更改或那些事件應觸發刷新整個表:

-(void) reloadData 

或某些單元格:

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

只有這樣,單元格才會被更新。

在TransportCell中嘗試此方法,它的快速代碼與目標c相同

override func layoutSubviews() 
{
 self.backgroundView.backgroundColor = [UIColor redColor];
}

您正在更改self.backgroundview.backgroundColor

默認情況下它是nil對細胞UITableViewStylePlain ,以及非空的UITableViewStyleGrouped

“ backgroundView”將作為子視圖添加到所有其他視圖的后面。

@property (nonatomic, strong, nullable) UIView *backgroundView;

用這個:

self.contentView.backgroundColor = [UIColor redColor];

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM