如何将按钮标题传递给不同视图控制器中的标签

时间:2016-01-07 12:51:06

标签: ios swift uiviewcontroller

在一个新项目中,我有2个视图控制器(View1和View2) 我在View1中有一个按钮,在View2中有一个标签。 当我在View1中按下此按钮时,我希望当我转移到View2页面时,按钮的名称/标题出现在View2的标签上。 我怎么能这样做?

我查看过这个页面但没有真正理解:Passing button title to a new view

2 个答案:

答案 0 :(得分:1)

创建一个新的CocoaTouch类SecondViewController,为UIViewController创建XIB的子类并为IBOutlet创建label

声明变量:

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

答案 1 :(得分:-1)

- 在View2上创建用于接受按钮标题的属性

@interface View2 : UIViewController {

}
@property (nonatomic, strong) IBOutlet UILabel *lblTitle;
@property (nonatomic, strong) NSString *btnTitle;

- (void)viewDidLoad {
    [super viewDidLoad];
   self.lblTitle.text = self.btnTitle;
}

在View1中

  @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

    }