ios 如何在 swift 3 中使用 addTarget 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39617873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use addTarget method in swift 3
提问by Ninja13
here is my button
object
这是我的button
对象
let loginRegisterButton:UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor(r: 50 , g: 80, b: 130)
button.setTitle("Register", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside)
return button
}()
and here is my function
这是我的功能
func handleRegister(){
FIRAuth.auth()?.createUser(withEmail: email, password: password,completion: { (user, error) in
if error != nil
{ print("Error Occured")}
else
{print("Successfully Authenticated")}
})
}
I'm getting compile error, if addTarget removed it compiles successfully
我收到编译错误,如果 addTarget 被删除,它编译成功
回答by Damien Romito
Yes, don't add "()" if there is no param
是的,如果没有参数,请不要添加“()”
button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside).
and if you want to get the sender
如果你想得到发件人
button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside).
func handleRegister(sender: UIButton){
//...
}
Edit:
编辑:
button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside)
no longer works, you need to replace _
in the selector with a variable name you used in the function header, in this case it would be sender
, so the working code becomes:
不再有效,您需要_
在选择器中替换为您在函数头中使用的变量名,在本例中为sender
,因此工作代码变为:
button.addTarget(self, action:#selector(handleRegister(sender:)), for: .touchUpInside)
回答by Soumen
Try this with Swift 4
用 Swift 4 试试这个
buttonSection.addTarget(self, action: #selector(actionWithParam(_:)), for: .touchUpInside)
@objc func actionWithParam(sender: UIButton){
//...
}
buttonSection.addTarget(self, action: #selector(actionWithoutParam), for: .touchUpInside)
@objc func actionWithoutParam(){
//...
}
回答by VRAwesome
Try this
尝试这个
button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside).
Just add parenthesis with name of method.
只需添加带有方法名称的括号。
Also you can refer link : Value of type 'CustomButton' has no member 'touchDown'
您也可以参考链接:“CustomButton”类型的值没有成员“touchDown”
回答by eranda.del
Try with swift 3
尝试使用 swift 3
cell.TaxToolTips.tag = indexPath.row
cell.TaxToolTips.addTarget(self, action: #selector(InheritanceTaxViewController.displayToolTipDetails(_:)), for:.touchUpInside)
@objc func displayToolTipDetails(_ sender : UIButton) {
print(sender.tag)
let tooltipString = TaxToolTipsArray[sender.tag]
self.displayMyAlertMessage(userMessage: tooltipString, status: 202)
}
回答by Giang
let button: UIButton = UIButton()
button.setImage(UIImage(named:"imagename"), for: .normal)
button.addTarget(self, action:#selector(YourClassName.backAction(_sender:)), for: .touchUpInside)
button.frame = CGRect.init(x: 5, y: 100, width: 45, height: 45)
view.addSubview(button)
@objc public func backAction(_sender: UIButton) {
}
回答by Nikhil Manapure
In swift 3 use this -
在 swift 3 中使用这个 -
object?.addTarget(objectWhichHasMethod, action: #selector(classWhichHasMethod.yourMethod), for: someUIControlEvents)
For example(from my code) -
例如(来自我的代码)-
self.datePicker?.addTarget(self, action:#selector(InfoTableViewCell.datePickerValueChanged), for: .valueChanged)
Just give a :
after method name if you want the sender as parameter.
:
如果您希望发件人作为参数,只需在方法名称之后给出。
回答by S E
Try this with Swift 3
用 Swift 3 试试这个
button.addTarget(self, action:#selector(ClassName.handleRegister(sender:)), for: .touchUpInside)
Good luck!
祝你好运!
回答by hlp
The poster's second comment from September 21st is spot on. For those who may be coming to this thread later with the same problem as the poster, here is a brief explanation. The other answers are good to keep in mind, but do not address the common issue encountered by this code.
从 9 月 21 日开始,海报的第二条评论是正确的。对于那些稍后可能会遇到与海报相同问题的人,这里是一个简短的解释。其他答案很好记住,但不解决此代码遇到的常见问题。
In Swift, declarations made with the let
keyword are constants. Of course if you were going to add items to an array, the array can't be declared as a constant, but a segmented control should be fine, right?! Not if you reference the completed segmented control in its declaration.
在 Swift 中,使用let
关键字进行的声明是常量。当然如果你要向数组中添加项,数组不能声明为常量,但是分段控件应该没问题,对吧?!如果您在其声明中引用已完成的分段控件,则不会。
Referencing the object (in this case a UISegmentedControl
, but this also happens with UIButton
) in its declarationwhen you say .addTarget
and let the target be self
, things crash. Why? Because self
is in the midst of being defined. But we do want to define behaviour as part of the object... Declare it lazilyas a variable with var
. The lazy
fools the compiler into thinking that self
is well defined - it silences your compiler from caring at the time of declaration. Lazily declared variables don't get set until they are first called. So in this situation, lazy
lets you use the notion of self
without issue while you set up the object, and then when your object gets a .touchUpInside
or .valueChanged
or whatever your 3rd argument is in your .addTarget()
, THENit calls on the notion of self
, which at that point is fully established and totally prepared to be a valid target. So it lets you be lazy in declaring your variable. In cases like these, I think they could give us a keyword like necessary
, but it is generally seen as a lazy, sloppy practice and you don't want to use it all over your code, though it may have its place in this sort of situation. What it
当您说并让目标为 时,在其声明中引用对象(在本例中为 a UISegmentedControl
,但这也与 一起发生UIButton
),事情会崩溃。为什么?因为正在被定义。但是我们确实想将行为定义为对象的一部分……用懒惰地将其声明为变量。该傻瓜编译成以为是明确的-它从沉默关心你的编译器在声明的时间。延迟声明的变量在第一次被调用之前不会被设置。因此,在这种情况下,让您在设置对象时使用无问题的概念,然后当您的对象获得或.addTarget
self
self
var
lazy
self
lazy
self
.touchUpInside
.valueChanged
或者无论你的 3rd 参数是什么.addTarget()
,那么它都会调用 的概念self
,在这一点上它已经完全建立并完全准备好成为一个有效的目标。所以它让你懒惰地声明你的变量。在这种情况下,我认为他们可以给我们一个关键字 like necessary
,但它通常被视为一种懒惰、草率的做法,你不想在你的代码中使用它,尽管它可能在这种情况下占有一席之地情况。什么
There is no lazy let
in Swift (no lazy
for constants).
有没有lazy let
在斯威夫特(不lazy
为常数)。
Here is the Apple documentation on lazy.
Here is the Apple on variables and constants. There is a little more in their Language Reference under Declarations.
这是Apple 关于变量和常量。在他们的 Language Reference 下的Declarations 中还有更多内容。
回答by Edward Pizzurro
Instead of
代替
let loginRegisterButton:UIButton = {
//... }()
Try:
尝试:
lazy var loginRegisterButton:UIButton = {
//... }()
That should fix the compile error!!!
那应该修复编译错误!!!
回答by Zgpeace
the Demo from Apple document. https://developer.apple.com/documentation/swift/using_objective-c_runtime_features_in_swift
来自 Apple 文档的 Demo。https://developer.apple.com/documentation/swift/using_objective-c_runtime_features_in_swift
import UIKit
class MyViewController: UIViewController {
let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// without parameter style
let action = #selector(MyViewController.tappedButton)
// with parameter style
// #selector(MyViewController.tappedButton(_:))
myButton.addTarget(self, action: action, forControlEvents: .touchUpInside)
}
@objc func tappedButton(_ sender: UIButton?) {
print("tapped button")
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}