![](/img/trans.png)
[英]I can't connect TableViewCell button to TableViewController! How do I connect values from TableViewCell to TableViewController?
[英]How can I access a TableViewController's variable in a subclassed TableViewCell file?
我在TableViewController中有一組朋友ID號,我用它來設置每個單元格的標題。 在我的子類TableViewCell中,我有一個按鈕,用於刪除與單元格關聯的朋友。 我需要知道與單元格關聯的朋友ID號,以便在TableViewCell代碼中進行HTTP調用。
如何在子類TableViewCell中訪問我的Friend ID數組? 有沒有更好的方法呢?
聽起來你不應該在UITableViewCell中執行該邏輯,而是在控制器或其他類中完成。
您應該找到一種方法讓單元格向控制器表明按鈕已被按下,並讓視圖控制器(或者更好的是,視圖控制器為業務邏輯創建的對象)。
我最喜歡這樣做的方法是在單元格上為要點擊的按鈕定義一個塊屬性:
// Custom Cell Header
@property (nonatomic, copy) void(^onButtonTapped)();
@property (nonatomic, strong) NSNumber* friendId;
// Custom Cell Implementation
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.button = [UIButton new];
[self.button
addTarget:self
action:@selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside
];
[self.contentView addSubview:self.button];
}
return self;
}
- (void)buttonTapped:(id)sender
{
if (self.onButtonTapped) {
self.onButtonTapped(friendId);
}
}
// Configuring your cell
cell.textLabel.text = @"blah";
cell.friendId = theId;
cell.onButtonTapped = ^(NSNumber *friendId) {
// Do what you want with the friendId
// Most likely ask business logic object to do what it should
// with the friendId
};
最終,您希望將業務邏輯保持在視圖之外,並且最好在視圖控制器之外,因為視圖控制器很快就會充滿代碼和復雜性。
前段時間我在自定義單元格中詢問了UIControls。 在這里查看 :
我一直在做的是創建一個自定義對象來保存自定義單元格的信息。 例如,我有一個帶按鈕或textField的自定義單元格。 在Custom對象上,我為該特定單元格准備了屬性。 其中一個屬性可以是僅鏈接到該單元格的http地址。 另一個屬性可以是一個僅與該單元格相關聯的segueId ......你明白了。
它在開始時很混亂,但它是創建tableViews的有效方法。
我相信它應該適合你的情況。 據我所知,策略是跟蹤indexPath。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.