【问题标题】:Triggering a specific action in one viewcontroller from another从另一个视图控制器中触发特定操作
【发布时间】:2015-08-27 21:33:27
【问题描述】:

我是 swift 新手,非常感谢我能得到的所有帮助! 我的应用有两个 ViewController,第一个问“你感觉如何?”并通过按钮提供替代方案。当点击其中一个按钮时,会输入 ViewController2 并显示一个标签。

我在 ViewController2 中为标签中随机显示的每个按钮提供了不同的文本数组。我的问题是,应该属于每个特定按钮的不同数组,但无论“它们属于”哪个按钮,它们都被混合并显示。这混淆了文本,它们不再属于自己的按钮/替代品。

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 中拖动按钮并创建新操作,但没有成功。

请帮帮我:-)

【问题讨论】:

    标签: ios swift uiviewcontroller viewcontroller


    【解决方案1】:

    对于您的示例,为每个按钮使用 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];
    }
    

    【讨论】:

      【解决方案2】:

      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 平台上的编程基于委托,因此学习委托是解决问题的第一步。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多