菜鸟教程小白 发表于 2022-12-11 17:05:13

ios - UIButton.addTarget 与 swift 3 和本地功能


                                            <p><p>我正在尝试以编程方式生成多个按钮。目前,这是我所拥有的:</p>

<pre><code>    for i in POIArray {

      let newI = i.replacingOccurrences(of: &#34;GPS30&#34;, with: &#34;&#34;)

      let button = UIButton(type: .custom)
      button.setImage(UIImage(named: newI), for: .normal)

      button.frame.size.height = 30
      button.frame.size.width = 30

      button.addTarget(self, action: #selector(buttonAction(texte:newI)), for: UIControlEvents.touchUpInside)
      XIBMenu?.stackMenuIco.addArrangedSubview(button)

    }
</code></pre>

<p>还有我的功能:</p>

<pre><code>      func buttonAction(texte: String) {
            print(&#34;Okay with \(texte)&#34;)
      }
</code></pre>

<p>当我删除参数“texte”时,它正在工作。按钮很好地添加到堆栈中,但我需要该参数来传递变量。我收到构建时错误:</p>

<pre><code>Argument of &#39;#selector&#39; does not refer to an &#39;@objc&#39; method, property, or initializer
</code></pre>

<p>是的,谢谢 XCode,我知道这不是 objc 方法,因为我正在快速编码!</p>

<p>有人知道方法吗?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>这里需要用到<code>objc_setAssociatedObject</code></p>

<p>在项目中添加扩展:-</p>

<pre><code>extension UIButton {
private struct AssociatedKeys {
    static var DescriptiveName = &#34;KeyValue&#34;
}

@IBInspectable var descriptiveName: String? {
    get {
      return objc_getAssociatedObject(self, &amp;AssociatedKeys.DescriptiveName) as? String
    }
    set {
      if let newValue = newValue {
            objc_setAssociatedObject(
                self,
                &amp;AssociatedKeys.DescriptiveName,
                newValue as NSString?,
                objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
            )
      }
    }
}
}
</code></pre>

<p>如何使用:-</p>

<pre><code>//let newI = i.replacingOccurrences(of: &#34;GPS30&#34;, with: &#34;&#34;)
button?.descriptiveName = &#34;stringData&#34; //newI use here
</code></pre>

<p>如何获取参数:-</p>

<pre><code>func buttonAction(sender: UIButton!) {
            print(sender.descriptiveName)
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - UIButton.addTarget 与 swift 3 和本地功能,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/38542171/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/38542171/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - UIButton.addTarget 与 swift 3 和本地功能