Unable to add target to UIButton - ios

I have a UIButton that I created programmatically. I have added a target to it, but it doesn't seem to be running properly. Here is my code (This is a custom class of UIView):
override init(frame: CGRect) {
super.init(frame: frame)
print("targets:")
print(clickButton.allTargets())
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
print("targets:")
print(clickButton.allTargets())
}
This is what prints as a result:
As you can see, adding a target to my button does not make a difference. Here is the clickPicture function:
func clickPicture() {
print("clickpicture")
}
Again, this does not print. Does anybody know how to fix this error? Thanks!
Edit:
Definition for clickButton (in my custom class):
var clickButton = UIButton()
Other properties defined in the init:
clickButton.frame.size = CGSize(width: 100, height: 100)
clickButton.layer.cornerRadius = clickButton.frame.size.width / 2
clickButton.layer.borderColor = UIColor.white().cgColor
clickButton.layer.borderWidth = 2.5
clickButton.layer.backgroundColor = shadeColor.cgColor
clickButton.center.x = self.center.x
clickButton.center.y = self.frame.size.height - clickButton.frame.size.height// + 40
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
self.addSubview(clickButton)

The button was not on top of the custom view when I instantiated it. I changed its position, and it worked fine.

You have to change this line
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
to this
clickButton.addTarget(self, action: #selector(YourClassName.clickPicture), forControlEvents: UIControlEvents.TouchUpInside)
And the method should be
func clickPicture() {
print("clickpicture")
}

Related

Trigger action from UIButton click on custom XIB

I am building a quote app using TGLParallaxCarousel library in my project. I try to custom the CustomView of TGLParallaxCarouselItem by adding two UIButtons (favButton and shareButton) on it.
screenshot to the quote cards (CustomView) I create
I am able to change the UIButton view based on its state--whether the current quote is faved or not, by doing this:
convenience init(frame: CGRect, number: Int) {
self.init(frame: frame)
currentQuote = quoteData[number]
favButton.tag = number
currentQuote.faved == true ? favButton.setImage(#imageLiteral(resourceName: "fav-on"), for: .normal) : favButton.setImage(#imageLiteral(resourceName: "fav-off"), for: .normal)
}
However I need to be able to turn the fav on and off by clicking the favButton. I tried to connect the favButton directly as an IBAction to the XIB file, tried to addAction to function, but I still can't access the favButton click state.
Please help. What should I do?
UPDATE
I've tried addTarget on favButton. It's not working. My tap is detected as tap on CustomView rather than specifically on favButton.
Here's the detectTap function that fired when I tap anywhere on the CustomView (including on the favButton). This function is within the TGLParallaxCarousel.swift
func detectTap(_ recognizer:UITapGestureRecognizer) {
let targetPoint: CGPoint = recognizer.location(in: recognizer.view)
currentTargetLayer = mainView.layer.hitTest(targetPoint)!
guard let targetItem = findItemOnScreen() else { return }
let firstItemOffset = (items.first?.xDisp ?? 0) - targetItem.xDisp
let tappedIndex = -Int(round(firstItemOffset / xDisplacement))
self.delegate?.carouselView(self, didSelectItemAtIndex: tappedIndex)
if targetItem.xDisp == 0 {
self.delegate?.carouselView(self, didSelectItemAtIndex: tappedIndex)
}
else {
selectedIndex = tappedIndex
}
}
Did you try to use addTarget?
convenience init(frame: CGRect, number: Int) {
self.init(frame: frame)
currentQuote = quoteData[number]
favButton.tag = number
currentQuote.faved == true ? favButton.setImage(#imageLiteral(resourceName: "fav-on"), for: .normal) : favButton.setImage(#imageLiteral(resourceName: "fav-off"), for: .normal)
favButton.addTarget(self, action: #selector(toggle), for: .touchUpInside)
}
#objc fileprivate func toggle() {
currentQuote.faved = !currentQuote.faved
currentQuote.faved == true ? favButton.setImage(#imageLiteral(resourceName: "fav-on"), for: .normal) : favButton.setImage(#imageLiteral(resourceName: "fav-off"), for: .normal)
}

How to use addTarget method in swift 3. Convert 2.3 to 3.0 [duplicate]

here is my button object
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
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:
button.addTarget(self, action:#selector(handleRegister(sender:)), for: .touchUpInside)
Try this with 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(){
//...
}
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'
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) {
}
Try with 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)
}
In swift 3 use this -
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.
Try this with Swift 3
button.addTarget(self, action:#selector(ClassName.handleRegister(sender:)), for: .touchUpInside)
Good luck!
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.
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.
Referencing the object (in this case a UISegmentedControl, but this also happens with UIButton) in its declaration when 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 lazily as 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(), THEN it 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
There is no lazy let in Swift (no lazy for constants).
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.
Instead of
let loginRegisterButton:UIButton = {
//... }()
Try:
lazy var loginRegisterButton:UIButton = {
//... }()
That should fix the compile error!!!
the Demo from Apple document. 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)
}
}

Button control doesn't respond to taps in Swifty `Player` package view controller

Using pod 'Player' in an iOS 9.0 app to play a video. I've subclassed Player class to add a UIButton overlay for closing the window.
It appears fine and has highlighting animation when tapped, but closeTapped isn't called when touching up inside.
import UIKit
import Player
class PlayerViewController: Player, PlayerDelegate {
func install() {
view.frame = presentor.view.bounds
presentor.addChildViewController(self)
presentor.view.addSubview(view)
didMove(toParentViewController: presentor)
let closeImage = UIImage(named: "close")!
let closeButton = UIButton(type: .custom)
view.addSubview(closeButton)
closeButton.setImage(closeImage, for: .normal)
closeButton.autoPinEdge(toSuperviewEdge: .top, withInset: 25)
closeButton.autoPinEdge(toSuperviewEdge: .right, withInset: 15)
closeButton.autoSetDimensions(to: CGSize(width: 50, height: 50))
closeButton.addGestureRecognizer(UITapGestureRecognizer())
closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
}
func closeTapped() {
logger.debug("Player close tapped")
}
}
I also tried having closeTapped(sender: Any?), didn't help.
Why isn't closeTapped called?
You don't need to add a TapGestureRecognizer to the button. For swift 3.0 you can do it like this:
button.addTarget(self, action: #selector(closeTapped(sender:)), for: .touchUpInside)
func closeTapped(sender: UIButton) {
}
I think the top of your button u added a UITapGestureRecognizer(). Which itself has a #selector. So Your button default .touchUpInside controller is not calling.
Try with commenting
//closeButton.addGestureRecognizer(UITapGestureRecognizer())
this line.
Let me know is this helpful or not.

How to use addTarget method in swift 3

here is my button object
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
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:
button.addTarget(self, action:#selector(handleRegister(sender:)), for: .touchUpInside)
Try this with 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(){
//...
}
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'
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) {
}
Try with 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)
}
In swift 3 use this -
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.
Try this with Swift 3
button.addTarget(self, action:#selector(ClassName.handleRegister(sender:)), for: .touchUpInside)
Good luck!
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.
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.
Referencing the object (in this case a UISegmentedControl, but this also happens with UIButton) in its declaration when 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 lazily as 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(), THEN it 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
There is no lazy let in Swift (no lazy for constants).
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.
Instead of
let loginRegisterButton:UIButton = {
//... }()
Try:
lazy var loginRegisterButton:UIButton = {
//... }()
That should fix the compile error!!!
the Demo from Apple document. 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)
}
}

cosmicmind material swift MenuView not closing

I am using cosmicmind material swift library and am following the examples code to try to get the FAB MenuView working.
I have copied the code and added the buttons i want, to test i am just testing with 2 buttons. The problem I am facing is with the handleMenu function:
/// Handle the menuView touch event.
internal func handleMenu() {
if menuView.menu.opened {
menuView.close()
(menuView.menu.views?.first as? MaterialButton)?.animate(MaterialAnimation.rotate(rotation: 0))
} else {
menuView.menu.open() { (v: UIView) in
(v as? MaterialButton)?.pulse()
}
(menuView.menu.views?.first as? MaterialButton)?.animate(MaterialAnimation.rotate(rotation: 0.125))
}
}
The full code for this UINavigationController:
import UIKit
import Material
class MyTeeUpsController: UINavigationController {
/// MenuView reference.
private lazy var menuView: MenuView = MenuView()
/// Default spacing size
let spacing: CGFloat = 16
/// Diameter for FabButtons.
let diameter: CGFloat = 56
/// Handle the menuView touch event.
internal func handleMenu() {
if menuView.menu.opened {
menuView.close()
(menuView.menu.views?.first as? MaterialButton)?.animate(MaterialAnimation.rotate(rotation: 0))
} else {
menuView.menu.open() { (v: UIView) in
(v as? MaterialButton)?.pulse()
}
(menuView.menu.views?.first as? MaterialButton)?.animate(MaterialAnimation.rotate(rotation: 0.125))
}
}
/// Handle the menuView touch event.
internal func handleButton(button: UIButton) {
print("Hit Button \(button)")
}
private func prepareMenuView() {
//let w: CGFloat = 52
var img:UIImage? = MaterialIcon.cm.add?.imageWithRenderingMode(.AlwaysTemplate)
let button1: FabButton = FabButton()//frame: CGRectMake((view.bounds.width - w)-10, 550,w,w))
button1.setImage(img, forState: .Normal)
button1.setImage(img, forState: .Highlighted)
button1.pulseColor = MaterialColor.blue.accent3
button1.backgroundColor = MaterialColor.blueGrey.lighten1
button1.borderColor = MaterialColor.blue.accent3
button1.borderWidth = 1
button1.addTarget(self, action: #selector(handleMenu), forControlEvents: .TouchUpInside)
menuView.addSubview(button1)
img = UIImage(named: "filing_cabinet")?.imageWithRenderingMode(.AlwaysTemplate)
let button2:FabButton = FabButton()
button2.depth = .None
button2.setImage(img, forState: .Normal)
button2.setImage(img, forState: .Highlighted)
button2.pulseColor = MaterialColor.blue.accent3
button2.borderColor = MaterialColor.blue.accent3
button2.borderWidth = 1
button2.backgroundColor = MaterialColor.blueGrey.lighten1
button2.addTarget(self, action: #selector(handleButton), forControlEvents: .TouchUpInside)
menuView.addSubview(button2)
menuView.menu.direction = .Up
menuView.menu.baseSize = CGSizeMake(diameter, diameter)
menuView.menu.views = [button1,button2]
view.layout(menuView).width(diameter).height(diameter).bottomRight(bottom: 58, right: 20)
}
private func prepareTabBarItem() {
//todo
}
override func viewDidLoad() {
super.viewDidLoad()
prepareMenuView()
}
}
The menu I have embedded as a subView of UINavigationController. The reason I have added to this subView is because the FAB is on top of a search/display controller (TableView) and this way the FAB can remain on top of the TableView even when scrolling the contents of the Table.
When the view initially loads, I can click on the menu button and the animation happens correctly and button2 appears. However, it does not allow me to hit the second button OR close the menu by pressing button1 again UNLESS I navigate to another tab in the tab bar controller and then navigate back to the tab where the FAB MenuView was located. I am loading my prepareMenuView() function in viewDidLoad just as it is shown in the example.
Not sure how to modify this so that it can behave as desired. It doesn't make sense to pick another ViewController lifecycle method to run prepareMenuView().
so the issue with your code is that button2 only has the selector handler for handleButton. The handleMenu handler is not added to it. So you have two solutions.
Add the handleMenu call to the handleButton
internal func handleButton(button: UIButton) {
print("Hit Button \(button)")
handleMenu(button)
}
Add a selector handler to the button2 instance for handleMenu.
button2.addTarget(self, action: #selector(handleMenu), forControlEvents: .TouchUpInside)
button2.addTarget(self, action: #selector(handleButton), forControlEvents: .TouchUpInside)
Either option will work, just remember that order matters. So if you want the menu to close before you load some content, then call the method before or add the selector handler handleMenu before you add the handleButton.
:) All the best!

Resources