好的,首先我必须说我在iOS领域有点像菜鸟。 那说我会进一步解释我的问题。
我正在制作一个用户获取动物列表的应用程序。当用户从列表中选择动物时 - >第二个viewcontroller打开,imageview必须设置为选定的动物+有动物的描述。
将这段代码放在viewController2.m的ViewDidLoad中
- (void)viewDidLoad
{
[super viewDidLoad];
[self.navigationItem setTitle:@"Animal"]; //here the title has to be set to the animal but I will try this later
// Do any additional setup after loading the view from its nib.
UIImage * cowImage = [UIImage imageNamed:@"cow.png"];
UIImage * horseImage = [UIImage imageNamed:@"horse.png"];
ViewController1 *viewController1 = [[ViewController1 alloc]init];
characterNumber = viewController1.pickedRow;
//set the uiimageview based on characternumber
switch (characterNumber) {
case 0:
foto.image = pukkelpopImage;
detailInfo.text = @"blabla";
[self.navigationItem setTitle:characterName];
break;
case 1:
foto.image = cactusImage;
break;
default:
break;
}
}
在我的ViewController 1.m中,我有这个方法来选择一个项目。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
ViewController2 *ViewController22 = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil];
[[self navigationController] pushViewController:ViewController22 animated:YES];
pickedRow = indexPath.row; //As you can see here I try to get which row was tapped
}
问题出在哪里? 感谢您阅读
答案 0 :(得分:1)
您正在viewController2中分配一个新的viewController1实例,该实例与推送viewController2的viewController1实例完全无关。
尝试在viewController2中声明一个NSInteger属性来存储拾取的行,并在将它推入didSelectRowAtIndexPath之前设置viewController2实例的值。
在ViewController2.h中声明属性:
@property (nonatomic) NSInteger pickedRow;
在ViewController1.m didSelectRowAtIndexPath中,在初始化viewController2实例之后设置属性,然后再推送它:
viewController2.pickedRow = indexPath.row;
无需在ViewController2.m中初始化viewController1:
// ViewController1 *viewController1 = [[ViewController1 alloc]init];
变量characterNumber可以用self.pickedRow替换。