2013-05-16 3 views
4

ok, это, возможно, вопрос новичков, но мне нужна помощь ... У меня есть someview.m, и в нем создана пользовательская ячейка, которая определена в customCell.h и .m Так someview.mi естьObject-c методы доступа из пользовательской ячейки

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath 
{ 
    customCell *cell=[tableView dequeueReusableCellWithIdentifier:@"charCell"]; 
if (cell == nil || (![cell isKindOfClass: customCell.class])) 
{ 
    cell=[[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"charCell"]; 
} 
return cell; 
} 

я есть метод слишком

-(void) printStuff 
{ 
    NSLog(@"stuff"); 
} 

Теперь пользовательские элементы работают нормально, но мне нужно, чтобы получить доступ к методу printStuff из

- (BOOL)textFieldShouldReturn:(UITextField *)textField 

, который находится в customCell.m я попробовал такие вещи, как [[self super] printStuff], но я всегда получаю сообщение об ошибке ... Я надеюсь, что я объяснил проблему правильно

+1

Предложение: Пожалуйста, следуйте за camelCasing при написании кода. 'customCell * cell' должен быть' CustomCell * cell' Выглядит профессионально :) –

ответ

2

если TextField находится в пользовательской ячейке, вы можете справиться textField ... события в тоже.

, если вы сделаете это, вы можете вызвать METHODE просто с [self printStuff]; в

- (BOOL)textFieldShouldReturn:(UITextField *)textField

//CustomCell.h 
// ... 
@interface CustomCell : UITableViewCell <UITextFieldDelegate> 
{ 
    //... 
} 

-(void)printStuff; 

@end 

//CustomCell.m 

//... 

-(void)printStuff 
{ 
    //... 
} 

-(BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
    //... 
    [textField resignFirstResponder]; 

    [self printStuff]; 

    return YES; 
} 

или если Methode printStuff в вас классе Tableview, вы можете объявить протокол

// CustomCell.h 
@protocol CustomCellProtocol <NSObject> 

-(void)printStuff:(NSString *)stuff; 

@end 

@interface CustomCell UITableViewCell <UITextFieldDelegate> 

@property (nonatomic, assign)UIViewController<CustomCellProtocol> *parent; 

// CustomCell.m 
-(void)printStuff:(NSString *)stuff 
{ 
    [parent printStuff:stuff]; 
} 


// TableViewClass.h 
... 
@interface TableViewClass : UITableViewController<CustomCellProtocol> 


// TableViewClass.m 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    customCell *cell=[tableView dequeueReusableCellWithIdentifier:@"charCell"]; 
    if (cell == nil || (![cell isKindOfClass: customCell.class])) 
    { 
     cell=[[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"charCell"]; 
     cell.parent = self; // or with a custom setter methode 
    } 
    return cell; 
} 
+0

Метод printStuff должен быть в someview.m (очевидно, это не метод simeple print-out) – user2165933

+0

Кстати, решение протокола является родительским независимым один, поэтому вы просто знаете, что ваш родитель отвечает на этот метод, и вы можете называть его без каких-либо предупреждений. практично, если вы будете использовать ячейку не только в этом классе;) – geo

+0

Спасибо, решение протокола сделало это. – user2165933

0

Вам необходимо использовать делегат. Пользовательский метод инициализации ячейки примет делегат некоторого вида. Для textFeild в CustomCell установите этот делегат. Что-то связывают это В CustomCell.h есть класс переменной

{ 
UIViewController *target; 
} 
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier withtarget:(UIViewController *)_target; 

В CustomCell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier withtarget:(UIViewController *)_target 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     // Initialization code 
     target = _target; 
} 

// Теперь вы можете использовать этот вызов [целевой printStuff];

В методе someView.m cellForRow вызывается этот метод инициализации для инициализации ячейки.

cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier withtarget:self ]; 
+0

Когда я пытаюсь [target printStuff], я получаю «Использование необъявленного идентификатора« target », вы имели в виду _target?» если я положил [_target printStuff], я получаю «переменная экземпляра _target является частной» ... – user2165933

+0

Теперь я получаю «Тип получателя UIViewController», например, сообщение не объявляет метод с селектором «printStuff», когда я пытаюсь [target printStuff] – user2165933

+0

Измените UIViewController на SomeView и импортируйте SomView.h – Durgaprasad

0

Сделайте свое UITableView глобальное

И -(BOOL)textFieldShouldReturn:(UITextField *)textField

добавить что-то вроде:

UITableViewCell *cell = [tableView cellForRowAtIndexPath:TheIndexPath]; 
[cell printStuff]; 
1

Возьмите 1 переменную в customCell.h как

@property (nonatomic,strong) UIView *parent; //Assuming someview is UIView, if it is UIViewController than change UIView to id 

теперь следующего метод

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath 
{ 
    customCell *cell=[tableView dequeueReusableCellWithIdentifier:@"charCell"]; 
if (cell == nil || (![cell isKindOfClass: customCell.class])) 
{ 
    cell=[[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"charCell"]; 
} 
cell.parent = self; 
return cell; 
} 

теперь в

-(BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
    [_parent printStuff]; //Call like this. 
    return YES; 
} 

Надеется, что это помогает, дай мне знать в случае любого запроса.

Смежные вопросы