Ios 如何在不同的视图控制器中将按钮标题传递给标签
在新项目中,我有两个视图控制器(View1和View2)。Ios 如何在不同的视图控制器中将按钮标题传递给标签,ios,swift,uiviewcontroller,Ios,Swift,Uiviewcontroller,在新项目中,我有两个视图控制器(View1和View2)。 我在View1中有一个按钮,在View2中有一个标签。 当我在View1中按下此按钮时,我希望在转到View2页面时,按钮的名称/标题显示在View2的标签中。 我该怎么做 我查看了此页面,但没有真正理解:-在View2上创建接受按钮标题的属性 @interface View2 : UIViewController { } @property (nonatomic, strong) IBOutlet UILabel *lblTitle
我在View1中有一个按钮,在View2中有一个标签。 当我在View1中按下此按钮时,我希望在转到View2页面时,按钮的名称/标题显示在View2的标签中。 我该怎么做
我查看了此页面,但没有真正理解:-在View2上创建接受按钮标题的属性
@interface View2 : UIViewController {
}
@property (nonatomic, strong) IBOutlet UILabel *lblTitle;
@property (nonatomic, strong) NSString *btnTitle;
- (void)viewDidLoad {
[super viewDidLoad];
self.lblTitle.text = self.btnTitle;
}
在视图1中
@interface View1 : UIViewController {
}
@property (nonatomic, strong) IBOutlet UIButton *btn;
- (void)myButtonClicked:(id)sender{
View1 *newViewController = [[View1 alloc] initWithNibName:'View1' bundle:nil];
newViewController.btnTitle = self.btn.titleLabel.text;
// push or present controller
}
创建一个新的CoCoatTouch类
SecondViewController
,子类化UIViewController
,包括XIB
,并为标签创建IBOutlet
声明一个变量:
var labelTitle:String代码>在SecondViewController
SecondViewController ViewDidLoad将如下所示:
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = labelTitle
}
// Whereas titleLabel is the UILabel Outlet connected from XIB
现在,在您的FirstViewController
中,点击按钮执行操作
添加以下内容
@IBAction func buttonAction(sender : UIButton) {
// If the VCs are in a storyboard you will need to get the storyboard to access them
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) as UIStoryboard
let secondVC = mainStoryboard.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController
secondVC.labelTitle = sender.titleLabel?.text
// If not do this
let secondVC = SecondViewController.init(nibName: "SecondViewController", bundle: nil)
secondVC.labelTitle = sender.titleLabel?.text
}
//Next present or push your ViewController
你不明白什么?我在输入时出错了。那是因为它们是obj-c格式的,而不是swift格式的-但是你明白答案试图解释如何解决问题的原理吗?我不太明白“你需要创建一个属性”B如何将labelTitle分配给UILabel的可能重复项?非常感谢!对于FirstViewController中的代码,我在第二行不断得到一个“预期声明”错误。什么是“按钮点击操作”?按钮点击操作是按钮上的iAction。请检查编辑过的答案你也可以用segue来做,不是吗?