ios - UIButton.addTarget 与 swift 3 和本地功能
<p><p>我正在尝试以编程方式生成多个按钮。目前,这是我所拥有的:</p>
<pre><code> for i in POIArray {
let newI = i.replacingOccurrences(of: "GPS30", with: "")
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("Okay with \(texte)")
}
</code></pre>
<p>当我删除参数“texte”时,它正在工作。按钮很好地添加到堆栈中,但我需要该参数来传递变量。我收到构建时错误:</p>
<pre><code>Argument of '#selector' does not refer to an '@objc' 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 = "KeyValue"
}
@IBInspectable var descriptiveName: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.DescriptiveName,
newValue as NSString?,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
)
}
}
}
}
</code></pre>
<p>如何使用:-</p>
<pre><code>//let newI = i.replacingOccurrences(of: "GPS30", with: "")
button?.descriptiveName = "stringData" //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]