I'm trying to learn how to create button target actions, however, when I press the button, I get those LLDB errors and I get told that it was an 'unrecognized selector sent to class'.
Where am I going wrong here?
StatusCell.swift:
let phoneIcon: UIButton = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.image = UIImage(named: "Phone3")?.imageWithRenderingMode(.AlwaysTemplate)
let phoneBtn = UIButton(type: .Custom)
phoneBtn.addTarget(CallButton.self, action: #selector(CallButton.buttonPressed(_:)), forControlEvents: .TouchDown)
phoneBtn.addTarget(CallButton.self, action: #selector(CallButton.buttonReleased(_:)), forControlEvents: .TouchUpInside)
phoneBtn.translatesAutoresizingMaskIntoConstraints = false
phoneBtn.setImage(iv.image!, forState: .Normal)
phoneBtn.tintColor = UIColor(r: 224, g: 224, b: 224)
return phoneBtn
}()
Here's the CallButton class where I call for buttonPressed and buttonReleased.
class CallButton: UIControl {
func buttonPressed(sender: AnyObject?) {
print("Pressed")
}
func buttonReleased(sender: AnyObject?) {
print("Let go")
}
}
The value for parameter target must be an instance of CallButton, not the type itself.
You are setting the class itself, not an instance, as the target of the action.
Therefore, the method you set as the action should be implemented as a class method, not an instance method:
class func buttonPressed(sender: AnyObject?) {
print("Pressed")
}
Related
The following code is located inside a subclass of UIView
I am setting up a cancelButton inside a closure:
private var cancelButtonClosure: UIButton = {
...
button.addTarget(self, action: #selector(cancel(_:)), for: .touchUpInside)
...
}()
And at first I instantiated the button inside a function like so:
func showConfirmationView(...) {
...
let cancelButton = self.cancelButtonClosure
...
addSubview(cancelButton)
...
}
However this resulted in the cancel function not being called at all (even though the layout was right and the button was highlighting)
So I made these change:
Removed the addTarget part from the cancelButtonClosure
Added the addTarget part inside the showConfirmationView function
So it looked like that:
func showConfirmationView(...) {
...
let cancelButton = self.cancelButtonClosure
cancelButton.addTarget(self, action: #selector(cancel(_:)), for: .touchUpInside)
...
addSubview(cancelButton)
...
}
It worked: the cancel function was called; but I don't know why. I'm really curious to know why what I did before did not work. Thanks for your insights!
Check your implementation because a setup like this works as expected:
private var cancelButton: UIButton = {
let btn = UIButton(type: .system)
btn.setTitle("Cancel", for: .normal)
btn.addTarget(self, action: #selector(cancelSomething(_:)), for: .touchUpInside)
return btn
}()
#objc func cancelSomething(_ sender: UIButton) {
print("Something has to be cancelled")
}
override func viewDidLoad() {
super.viewDidLoad()
showConfirmationView()
}
func showConfirmationView() {
cancelButton.sizeToFit()
cancelButton.center = view.center
view.addSubview(cancelButton)
}
I have a class where written is a function creating my button:
LoginButton.swift
func createButton() {
let myButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(Foo().buttonPressed(_:)), for: .touchUpInside)
}()
}
Now in my second class, Foo.swift, I have a function that just prints a statement
Foo.swift
#objc func buttonPressed(_ sender: UIButton) {
print("button was pressed")
}
When ran I get no errors except when I try to press the button, nothing happens. Nothing prints, the UIButton doesn't react in any way. Really not sure where the error occurs because Xcode isn't printing out any type of error or warning message.
The action method is called in the target object. Thus, you have either to move buttonPressed to the class which contains createButton or to pass an instance of Foo as a target object.
But note that a button is not the owner of its targets. So, if you just write:
button.addTarget(Foo(), action: #selector(buttonPressed(_:)), for: .touchUpInside)
This will not work, because the Foo object is immediately released after that line. You must have a strong reference (e.g. a property) to Foo() like
let foo = Foo()
func createButton() {
let myButton: UIButton = {
let button = UIButton()
button.addTarget(foo, action: #selector(buttonPressed(_:)), for: .touchUpInside)
}()
}
You are missing with target. So make instant of target globally and make use of it as target for button action handler.
class ViewController: UIViewController {
let foo = Foo()
override func viewDidLoad() {
super.viewDidLoad()
createButton()
}
func createButton() {
let myButton: UIButton = {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.backgroundColor = UIColor.red
button.setTitle("Tap me", for: .normal)
button.addTarget(self.foo, action: #selector(self.foo.buttonPressed(_:)), for: .touchUpInside)
return button
}()
myButton.center = self.view.center
self.view.addSubview(myButton)
}
}
Class Foo:
class Foo {
#objc func buttonPressed(_ sender: UIButton) {
print("button was pressed")
}
}
Just pass Selector as function argument.
func createButtonWith(selector: Selector) {
let myButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: selector), for: .touchUpInside)
}()
}
And call this function like below...
createButtonWith(selector: #selector(Foo().buttonPressed(_:)))
SquareBox.swift
class SquareBox {
func createBoxes() {
for _ in 0..<xy {
let button = UIButton()
button.backgroundColor = .white
button.setTitleColor(UIColor.black, for: .normal)
button.layer.borderWidth = 0.5
button.layer.borderColor = UIColor.black.cgColor
stack.addArrangedSubview(button)
button.addTarget(self, action: #selector(click(sender:)) , for: .touchUpInside)
}
}
#objc func click(sender : UIButton) {
print("Click")
}
}
ViewController.swift
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let boxRow = SquareBox()
boxRow.createBoxes()
}
}
Also I've tried #IBAction instead of #objc, it doesn't work, but if I use "click" function in ViewController.swift that I created this object, it's working but I need this function inside of this class.
Now that you have posted relevant information in your question, the problem is quite clear. You have a memory management issue.
In your GameViewController's viewDidLoad you create a local instance of SquareBox. This local instance goes out of scope at the end of viewDidLoad. Since there is no other reference to this instance, it gets deallocated at the end of viewDidLoad.
Since the instance of SquareBox has been deallocated, it is not around to act as the button's target. And your click method is never called.
The solution is to keep a reference in your view controller:
class GameViewController: UIViewController {
let boxRow = SquareBox()
override func viewDidLoad() {
super.viewDidLoad()
boxRow.createBoxes()
}
}
var btnfirst:UIButton!
override func viewDidLoad()
{
super.viewDidLoad()
btnfirst = UIButton(type: .system)
btnfirst.setTitle("Press", for: .normal)
btnfirst.setTitleColor(.red, for: .normal)
btnfirst.frame = CGRect(x: 100, y: 200, width: 100, height: 30)
btnfirst.addTarget(self, action: #selector(benpress( sender:)),for: .touchUpInside)
self.view.addSubview(btnfirst)
}
func benpress( sender :UIButton)
{
//Your Code Here
}
For those who did not find a solution, here is mine.
If you constructed your UIButton as
let button: UIButton = {
return UIButton()
}()
Just convert those into
lazy var button: UIButton = {
return UIButton()
}()
I think this is because of somewhat deallocation as mentioned above.
button.addTarget(self, action:#selector(self.click), for: .touchUpInside)
func click(sender : UIButton) {
// code here
}
I guess the issue is how you are setting up layout of your buttons.
Try this:
func createBoxes() {
stack.backgroundColor = UIColor.red
for _ in 0..<xy {
// Create the button
let button = UIButton()
button.backgroundColor = UIColor.red
// Add constraints
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true
// Setup the button action
button.addTarget(self, action: #selector(SquareBox.click(sender:)), for: .touchUpInside)
// Add the button to the stack
stack.addArrangedSubview(button)
}
}
#objc func click(sender : UIButton) {
print("Click")
}
button.addTarget(self, action: #selector(self.buttonTapped), for: .touchUpInside)
func buttonTapped(sender : UIButton) {
// code here
}
Replace with this :
btn.addTarget(self, action: #selector(self.click(sender:)), for: .touchUpInside)
I think something else effect to your selector method try to find in your code because your code also working in my project.
I have programmatically created a button in my main class and passing an instance of a game class (gameSCNScene - where most of the game logic lies) to the button. Inside this game class instance is where the action for the button resides however when ever I press the button I get the error - Unrecognized selector.
class GameViewController: UIViewController, SCNSceneRendererDelegate {
var gameSCNScene: GameSCNScene!
override func viewDidLoad() {
super.viewDidLoad()
let scnView = self.view as! SCNView
scnView.delegate = self
// Create my game scene instance
gameSCNScene = GameSCNScene(currentview: scnView)
// Make button
makeButtonsUI(gameSCNScene)
}
func makeButtonsUI(gameSCNScene: GameSCNScene) {
let image = UIImage(named: "art.scnassets/addBtn.png") as UIImage?
let button = UIButton(type: UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
button.setImage(image, forState: .Normal)
button.addTarget(self, action:("gameSCNScene.addCube:"), forControlEvents:.TouchUpInside)
self.view.addSubview(button)
}
Button function inside my gameSCNScene instance
func addCube(sender:UIButton) {
//Code here
}
The line of code where you add the target is incorrect. This:
button.addTarget(self, action:("gameSCNScene.addCube:"), forControlEvents:.TouchUpInside)
Should be:
button.addTarget(gameSCNScene, action:("addCube:"), forControlEvents:.TouchUpInside)
I have the following code.
import UIKit
class ViewController: UIViewController {
var button : UIButton?
override func viewDidLoad() {
super.viewDidLoad()
button = UIButton.buttonWithType(UIButtonType.System) as UIButton?
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I get the following error
ERROR:
'AnyObject' is not convertible to 'UIButton?'
I know I might be doing something fundamentally wrong. I would like to know what that is.
According to me:
I have declared button as an Optional UIButton
- Which I think means, that the value of button can be unset or nil
Therefore,
while initialising it the type is mentioned as UIButton?
Is this it right way ?
You can't cast to an optional UIButton in the way you're doing it. The correct way to cast to an optional UIButton is:
button = UIButton.buttonWithType(UIButtonType.System) as? UIButton
Interpret this as: This cast can either return nil or an UIButton object, resulting in an optional UIButton object.
Follow the below code
var myBtn = UIButton.buttonWithType(UIButtonType.System) as UIButton
//OR
var myBtn = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
//OR
var myBtn = UIButton()
myBtn.setTitle("Add Button To View Controller", forState: .Normal)
myBtn.setTitleColor(UIColor.greenColor(), forState: .Normal)
myBtn.frame = CGRectMake(30, 100, 200, 400)
myBtn.addTarget(self, action: "actionPress:", forControlEvents: .TouchUpInside)
self.view.addSubview(myBtn)
//Button Action
func actionPress(sender: UIButton!)
{
NSLog("When click the button, the button is %#", sender.tag)
}
Please try below code:
var button = UIButton(frame: CGRectMake(150, 240, 75, 30))
button.setTitle("Next", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
button.backgroundColor = UIColor.greenColor()
self.view.addSubview(button)
This code should do the job.
button = UIButton.buttonWithType(UIButtonType.System) as! UIButton
In this case the force cast done with the ! is a safe option because the documentation does guarantee that the method returns a UIButton.
You can also create the button during the declaration of the property:
class ViewController: UIViewController {
var button = UIButton.buttonWithType(UIButtonType.System) as! UIButton
...
This way there is no need to declare the property as an optional type.