从另一个 viewcontroller 中触发特定操作

Triggering a specific action in one viewcontroller from another

我是 swift 的新手,非常感谢能得到的所有帮助! 我的应用程序有两个 ViewController,第一个询问 "How are you feeling?" 并通过按钮提供替代方案。当点击其中一个按钮时,将进入 ViewController2 并显示一个标签。

我在 ViewController2 中为标签中随机显示的每个按钮设置了不同的文本数组。我的问题是,不同的数组应该分别属于一个特定的按钮,但无论哪个按钮 "they belong to" 都混合在一起显示。这混淆了文本,它们不再属于它们自己的 buttons/alternatives。

override func viewDidLoad() {
    super.viewDidLoad() 
//the ViewController2 has just been entered by clicking any button in ViewController1

    TextForButton1: NSArray = 
    ["EX1", "EX2", "EX3"]

    let rangeButton1: UInt32 = UInt32(TextForButton1.count)
    let randomNumberButton1 = Int(arc4random_uniform(rangeButton1))
    let StringButton1 = Button1.objectAtIndex(randomNumberButton1)
    self.Label.text = QuoteStringNervous as? String

  //New Button= supposed to be its own text 

    let TextForButton2: NSArray = ["EX4", "EX5", "EX6"]

    let rangeButton2: UInt32 = UInt32(TextForButton2.count)
    let randomNumberButton2 = Int(arc4random_uniform(rangeButton2))
    let StringButton2 = TextForButton2.objectAtIndex(randomNumberButton2)
    self.Label.text = QuoteStringFrustrated as? String

问题示例是:当点击 Button1 时,可以显示 "EX4"/"EX5"/"EX6",而不仅仅是 "EX1"/"EX2"/"EX3".

我知道 UIButtons 必须包含在代码中,但是在哪里?我曾尝试在 ViewController2 中拖动按钮并创建新操作,但没有成功。

请帮助我:-)

1) 你真的不应该在 Swift 中使用 NSArrays ... 2) 查看代表:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

http://code.tutsplus.com/tutorials/swift-from-scratch-delegation-and-properties--cms-23445

iOS 平台上的编程基于委托,因此学习委托是解决问题的第一步。

对于您的示例,最好为每个按钮使用一个 segue。然后在第一个视图控制器中,您可以确定哪个按钮激活了 segue,并使用 prepareForSegue 修改 destinationViewController 中的按钮标题。

例如,将按钮拖到视图控制器 1 中,添加 segue 动作以呈现视图控制器 2。

在视图控制器 1 的代码中,添加 prepareForSegue,添加 2 个按钮 IBOutlets,并将 iboutlets 连接到故事板。

还为每个按钮的 TouchUpInside 添加一个 IBAction,将控制器 1 中的变量设置为按下的按钮。

现在在 prepareForSegue 中检查按下的按钮,并根据它是哪个在视图控制器 2 中设置文本数组

就您在不同视图控制器中触发操作的实际问题...

还有NSNotification

在调用者中:

[[NSNotificationCenter defaultCenter] postNotificationNamed:@"DoSomethingNotification" userInfo:nil];

在接收者的viewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) forNotificationNamed:@"DoSomethingNotification"]]

并将函数添加到接收器

 -(void)doSomething:(NSNotification*)sender {
     // Perform action here
 }

别忘了将此添加到接收器:

-dealloc {
    [NSNotificationCenter defaultCenter] removeObserver:self];
}