1

我有 2 个 ViewController,在第一个 - TableView 和第二个 - 带有标签的按钮中。当我单击第二个 ViewController 中的按钮时,我需要返回 TableView 并设置

cell.detailTextLabel.text

按钮上标签的文本。

这是我的代码,但它不起作用:

视图控制器.h:

#import <UIKit/UIKit.h>
#import "TestControl.h"

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, myTestProtocol>
{
    TestControl *myProtocol;
}
@property (strong, nonatomic) IBOutlet UITableView * tableTest;

@end

视图控制器.m:

#import "ViewController.h"
#import "TestControl.h"

@implementation ViewController

@synthesize tableTest;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;

    myProtocol = [[TestControl alloc]init];
    myProtocol.delegate = self;

        // Do any additional setup after loading the view, typically from a nib.
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TestControl * test = [[TestControl alloc] initWithNibName:@"TestControl" bundle:nil];
    [self.navigationController pushViewController:test animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = @"Firs Cell";
            cell.detailTextLabel.text = myProtocol.myLabel.text;
            break;
        case 1:
            cell.textLabel.text = @"Second Cell";
            break;
        case 2:
            cell.textLabel.text = @"Third Cell";
            break;


        default:
            break;
    }

    return cell;
}
@end

测试控制.h:

#import <UIKit/UIKit.h>

@protocol myTestProtocol <NSObject>

@end

@interface TestControl : UIViewController
{
    UILabel *myLabel;
}

@property (nonatomic, assign) id <myTestProtocol> delegate;
@property (strong, nonatomic) IBOutlet UILabel *myLabel;

- (IBAction)testButton:(id)sender;
@end

测试控制.m:

@implementation TestControl

@synthesize myLabel;
@synthesize delegate;


- (IBAction)testButton:(id)sender
{
    myLabel.text = @"TEXT LABEL";
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];

}

这有什么问题???

4

1 回答 1

1

有几件事......

您正在创建两个不同TestControl的对象,为其中一个设置委托并推动另一个,因此处理按钮点击的对象没有委托。

反过来,委托逻辑会更好地工作。也就是说,TestControl应该有与其委托进行通信的代码,而不是委托从TestControl.

于 2012-08-10T23:41:04.957 回答