我在ViewController A
和tableview
上有一个按钮,ViewController B
上有自定义单元格。我想在ViewController B
的单元格上显示所选数据,作为button
上ViewController A
的当前标记。我知道这可以通过"代表"来实现。但我无法为它编码。如果有人告诉我代码,我会非常感激,因为我对iOS开发很新。
提前致谢!
答案 0 :(得分:0)
使用此代码:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()<SecondViewControllerPotocol>
@property (weak, nonatomic) IBOutlet UIButton *sampleButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)navigateToSecondVCOnButtonClick:(id)sender {
SecondViewController *second = (SecondViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"secondVC"];
second.delegate = self;
[self.navigationController presentViewController:second animated:YES completion:nil];
}
- (void)changeButtonTitleWithText:(NSString *)title{
[self.sampleButton setTitle:title forState:UIControlStateNormal];
}
@end
#import <UIKit/UIKit.h>
@protocol SecondViewControllerPotocol <NSObject>
@optional
- (void)changeButtonTitleWithText:(NSString *)title;
@end
@interface SecondViewController : UIViewController
//delegate
@property (nonatomic, assign) id<SecondViewControllerPotocol> delegate;
@end
SecondViewController.m
----
#import "SecondViewController.h"
@interface SecondViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *colorsTableView;
@property (strong, nonatomic) NSArray *colorsArray;
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.colorsTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
self.colorsArray = @[@"Red",@"Blue",@"Green",@"Yellow",@"Pink"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.colorsArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *customCell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
customCell.textLabel.text = self.colorsArray[indexPath.row];
return customCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
[_delegate changeButtonTitleWithText:selectedCell.textLabel.text];
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
请检查我的GitHub链接以测试示例项目(更改一个按钮标题):
https://github.com/k-sathireddy/CustomDelegateSample
如需更改两个按钮标题,请按照以下步骤操作: