如何在表视图中选择后将数据传递到详细视图? [英] How to pass data to detail view after being selected in a table view?
问题描述
我有一个UITableViewController,其中包含从名为userList的NSMutableArray填充的数据。选择特定用户后,它将转到详细视图,并更新NavBar中的标题,但它不会传递数据以更新UIView中的UILabel。
I have a UITableViewController that has data populated from an NSMutableArray called userList. When specific user is selected, it goes to a detail view, and updates the title in the NavBar, but it wont pass the data to update a UILabel in the UIView.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:NO];
//Attempt at a singleton to pass the data
DetailView *details = [[DetailView alloc] init];
details.userNameLbl = [userList objectAtIndex:indexPath.row];
DetailView *detailVC = [[DetailView alloc] initWithNibName:nil bundle:nil];
//This line doesn't pass the data
detailVC.userNameLbl.text = [userList objectAtIndex:indexPath.row];
//This line does update the title in the NavBar
detailVC.navigationItem.title = [userList objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailVC animated:YES];
[details release];
[detailVC release];
}
我是否应该尝试从表格视图中推送数据到详细视图,或者让详细视图尝试从表视图中提取数据?
Should I be trying to push the data from the table view to the detail view, or have the detail view try to pull the data from the table view?
DetailView.h实际上已连接到IB中的以下行。
DetailView.h has the following line that is in fact hooked up in IB.
IBOutlet UILabel *userNameLbl
推荐答案
在从nib文件加载视图之前,不会实例化 userNamelbl
。这不会在初始化时立即发生,但会在 viewDidLoad
被调用时发生。
The userNamelbl
isn't instantiated until the view is loaded from the nib file. This doesn't happen immediately at initialisation, but will have happened by the time viewDidLoad
is called.
所以,你应该在DetailView中声明一个属性来存储你的标题,然后在 viewDidLoad
userNamelbl.text >方法。
So, you should to declare a property in DetailView to store your title, and then assign that value to userNamelbl.text
in the viewDidLoad
method.
例如,在你的表中viewController:
For example, in your table viewController:
DetailView *detailVC = [[DetailView alloc] initWithNibName:nil bundle:nil];
detailVC.userName = [userList objectAtIndex: indexPath.row];
并在您的详细信息viewController中:
and in your detail viewController:
- (void) viewDidLoad
{
[super viewDidLoad];
self.userNameLbl.text = self.userName;
}
viewController的navigationItem属性是在viewController初始化时创建的,因此你可以分配立即到 navigationItem.title
。
The viewController's navigationItem property is created when the viewController is initialised, hence you can assign to the navigationItem.title
immediately.
Swift代码
let detailVC = DetailView(nibName: nil, bundle: nil)
detailVC.userName = userList.objectAtIndex(indexPath.row) as? NSString
和
class DetailView: UIViewController {
@IBOutlet var userNameLbl: UILabel
var userName:NSString?
override func viewDidLoad() {
super.viewDidLoad()
self.userNameLbl.text = self.userName
}
}
这篇关于如何在表视图中选择后将数据传递到详细视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!