【问题标题】:method to call on sender for UIButton为 UIButton 调用发送方的方法
【发布时间】:2015-07-26 00:52:03
【问题描述】:

所以我的页面上有一堆按钮,并将它们分类为 [UIButton] 类型的数组并称为buttonsArray。

当您单击其中一个按钮时,我会将它们的操作与 goToFacts 函数相关联,该函数与我的 segue “goToFactSegue”一起使用,并将 WHICH 按钮(发送者)的信息传递给我准备 segue 函数。我的 prepareforSegue 函数确认 segue 标识符是正确的,然后在 DetailViewController 页面上将变量索引设置为正确的数字。我计算设置索引的正确数字(称为whichIndex)的方法是匹配buttonsArray中的哪个索引(单击的按钮)。我的问题是找到被点击的按钮的标题/名称(发送者)并将其设置为 theButtonsName,这样我就可以在我的buttonsArray 中搜索它并找到它的索引。

TL;DR 如何像在 UIImageView 上使用 .view 一样提取 UIButton 的名称

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "goToFactSegue" {
        // send info to next page
        if let whereToGo = segue.destinationViewController as? DetailViewController {
            let theButtonsName = sender!.******** as! UIButton
            if let whichIndex = find(buttonsArray, theButtonsName) {
            whereToGo.index = whichIndex 
            }}
    }
}

@IBAction func goToFacts(sender: UIButton) {
    performSegueWithIdentifier("goToFactSegue", sender: sender)
}

我已经搜索了 xcode 建议的所有可能性,但没有与 UIButton 交互,阅读文档,他们谈论的只是 .titleLabel ,这是实际文本(不,.titleLabel 不起作用) 还尝试了通常的嫌疑人(命名...等的变体)

【问题讨论】:

  • 您不应尝试将 theButtonsName sender!.titleLabel!.text 转换为 UIButton 而是字符串。如果按钮上的 titleLabel 应该与它的值一起出现。

标签: swift cocoa-touch uibutton segue sender


【解决方案1】:

我建议您通过对您的应用功能的非常简短的解释来标记您的按钮。您可以使用情节提要执行此操作,使用 1、2、3、...、n 等值标记每个按钮,然后您将获得您似乎正在寻找的索引。 UIButton 有一个属性标签:

println("Tag of button: \(button.tag)")

发送者也是如此。

@IBAction func goToFacts(sender: UIButton) {
      performSegueWithIdentifier("goToFactSegue", sender: sender)
      whichIndex = sender.tag
}

【讨论】:

    【解决方案2】:
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    
        if segue.identifier == "goToFactSegue" {
    
           if let whereToGo = segue.destinationViewController as? DetailViewController {
    
             let button = sender as! UIButton
             let theButtonsName = button.titlelabel?.text
    
    
              if let whichIndex = find(buttonsArray, theButtonsName) {
                 whereToGo.index = whichIndex 
              }
           }
        }
    }
    

    【讨论】:

    • 比我快一秒 :) 正要发布——这就是我为修复错误所做的,谢谢 Shades!除了我没有把它分成两部分(因为它不是我们正在寻找的 titeLabel。只是取出有问题的代码,它就可以工作了。
    猜你喜欢
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 2018-07-07
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多