我遇到了同樣的問題,我通過將單元格繼承到它自己的類中,並將按鈕作爲插座並使用模型中的數據填充單元格,同時使用一種返回當前正在查看的單元格的方法。
舉例來說,如果你有一個Person類,每個人有一個名字,姓氏,和一些朋友。而且每次在單元格中點擊一個按鈕時,朋友對一個具體的人的數量將增加1
_______________DATA SOURCE___________________________
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *comment;
@property (nonatomic) NSInteger numberOfFriends;
+(instancetype)personWithName:(NSString *)aName Surname:(NSString *)aSurname;
@end
#import "Person.h"
@implementation Person
+(instancetype)personWithName:(NSString *)aName Surname:(NSString *)aSurname{
Person *person = [[Person alloc] init];
[person setName:aName];
[person setSurname:aSurname];
[person setNumberOfFriends:0];
return person;
}
@end
_____________________PERSON CELL________________________
#import <UIKit/UIKit.h>
@interface PersonCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *friendsNum;
@property (strong, nonatomic) IBOutlet UIButton *friendsBtn;
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet UILabel *surnameLabel;
@end
個人而言,我創建了一個私人的NSArray持有我一個人對象的名稱和一個私人的NSMutableDictionary增加來保存我的Person對象,並且我將這些鍵設置爲人員的名字。
_____________________PERSON TABLE VIEW________________________
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
PersonCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *name = [peopleNames objectAtIndex:indexPath.row];
Person *person = [people objectForKey:name];
if(cell == nil)
{
cell = [[PersonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.nameLabel.text = person.name;
cell.surname.Label.text = person.surname
[cell.friendsButton addTarget:self action:@selector(moreFriends:) forControlEvents:UIControlEventTouchUpInside];
cell.friendsNum.text = [NSString stringWithFormat:@"%i", person.numberOfFriends];
return cell;
}
- (IBAction)moreFriends:(id)sender {
UIButton *btn = (UIButton *)sender;
PersonCell *cell = [self parentCellForView:btn];
Person *person = [people objectForKey:cell.nameLabel.text];
person.numberOfFriends++;
[self.tableView reloadData];
}
-(PersonCell *)parentCellForView:(id)theView
{
id viewSuperView = [theView superview];
while (viewSuperView != nil) {
if ([viewSuperView isKindOfClass:[PersonCell class]]) {
return (PersonCell *)viewSuperView;
}
else {
viewSuperView = [viewSuperView superview];
}
}
return nil;
}
我覺得NSNotificationCenter是一個合理的策略。您沒有收到按鈕的操作方法發送或其他問題的通知嗎? –
我也這麼認爲 - 我不認爲我有實施他們的訣竅呢......更多的實踐。我現在可以讓他們在相同的視圖下工作,但是當我嘗試不同的視圖時仍然會出現異常......我們會到達 –
這是關於創建和使用委託協議的非常完整的解釋。 http://www.dosomethinghere.com/2009/07/18/setting-up-a-delegate-in-the-iphone-sdk/ – MystikSpiral