UIButton will not respond - ios

I'm currently working through Apple's Swift tutorial. In it, i am trying to make a custom button respond to tap and in turn print to the console. It seems to not be responding at all to any taps, or at the very least will not print it's response to the console.
Code is below, if anymore is needed please let me know.
import UIKit
class RatingControl: UIView {
//MARK: Initializaion
required init?(coder aDecoder: NSCoder) { // overrides it's superclass implementation of the initializer
super.init(coder: aDecoder)
let button = UIButton(frame: CGRect(x:0, y:0, width: 44, height: 44))
button.backgroundColor = UIColor.redColor()
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown)
addSubview(button)
func intrensicContentSize() -> CGSize {
return CGSize(width: 240, height: 44)
}
}
//MARK: Button Action
func ratingButtonTapped(button:UIButton) {
print("will it print?")
}
}

Please try .TouchUpInside instead of TouchDown
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchUpInside)

Related

Swift - Refresh Custom UITabBarController Bar

I have a custom TabBar, with a raised middle button, above the TabBar. When the user has not completed a daily task, the setupIncompleteMiddleButton() should appear, indicating that. However, once the user completes the task, I would like setupCompleteMiddleButton() to appear, indicating the have completed the task. I don't know how to do this - I shouldn't call viewDidLoad() in the controller and when calling it, it does nothing to refresh the view. Refreshing the TabBar does nothing.
This is my TabBar controller:
class TabBarController: UITabBarController, UITabBarControllerDelegate {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override func viewDidLoad() {
super.viewDidLoad()
// This is where I currently decide which button to show the "complete" one if the task is done, and the incomplete one if not.
self.delegate = self
if UserData.hasCompletedDailyTask() == true {
setupCompleteMiddleButton()
} else {
setupIncompleteMiddleButton()
}
}
// Incomplete button
func setupIncompleteMiddleButton() {
let middleButton = UIButton(frame: CGRect(x: (self.view.bounds.width / 2) - 25, y: -20, width: 50, height: 50))
middleButton.backgroundColor = UIColor.systemYellow
middleButton.setImage(UIImage(systemName: "sun.max.fill"), for: .normal)
middleButton.imageView?.tintColor = UIColor.white
middleButton.layer.cornerRadius = middleButton.frame.width / 2
middleButton.clipsToBounds = true
self.tabBar.addSubview(middleButton)
middleButton.addTarget(self, action: #selector(self.middleButtonAction), for: .touchUpInside)
self.view.layoutIfNeeded()
}
// Complete button
func setupCompleteMiddleButton() {
let middleButton = UIButton(frame: CGRect(x: (self.view.bounds.width / 2) - 25, y: -20, width: 50, height: 50))
middleButton.backgroundColor = UIColor.systemGreen
middleButton.setImage(UIImage(systemName: "checkmark"), for: .normal)
middleButton.imageView?.tintColor = UIColor.white
middleButton.layer.cornerRadius = middleButton.frame.width / 2
middleButton.clipsToBounds = true
self.tabBar.addSubview(middleButton)
middleButton.addTarget(self, action: #selector(self.middleButtonAction), for: .touchUpInside)
self.view.layoutIfNeeded()
}
#objc func middleButtonAction(sender: UIButton) {
self.selectedIndex = 1
}
}
Thank you!
You can try this for globally single object of button and just change the image whenever task is complete or not.
class TabBarController: UITabBarController, UITabBarControllerDelegate {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
// TabbarController hode this button
var middleButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setupButton()
// This is where I currently decide which button to show the "complete" one if the task is done, and the incomplete one if not.
self.delegate = self
// taskCompletion is a call back when UserData finish its task
if UserData.taskCompletion {
setupCompleteMiddleButton()
} else {
setupIncompleteMiddleButton()
}
}
func setupButton() {
middleButton = UIButton(frame: CGRect(x: (self.view.bounds.width / 2) - 25, y: -20, width: 50, height: 50))
middleButton.backgroundColor = UIColor.systemYellow
middleButton.layer.cornerRadius = middleButton.frame.width / 2
middleButton.clipsToBounds = true
self.tabBar.addSubview(middleButton)
middleButton.addTarget(self, action: #selector(self.middleButtonAction), for: .touchUpInside)
self.view.layoutIfNeeded()
}
// Incomplete button
func setupIncompleteMiddleButton() {
middleButton.backgroundColor = UIColor.systemYellow
middleButton.setImage(UIImage(systemName: "sun.max.fill"), for: .normal)
}
// Complete button
func setupCompleteMiddleButton() {
// change button color and image
middleButton.backgroundColor = UIColor.systemGreen
middleButton.setImage(UIImage(systemName: "checkmark"), for: .normal)
}
#objc func middleButtonAction(sender: UIButton) {
self.selectedIndex = 1
}
Maybe you can try this:
import UIKit
class TabBarController: UITabBarController, UITabBarControllerDelegate {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
// TabbarController hode this button
var middleButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// This is where I currently decide which button to show the "complete" one if the task is done, and the incomplete one if not.
self.delegate = self
// taskCompletion is a call back when UserData finish its task
if UserData.taskCompletion {
setupCompleteMiddleButton()
}
setupIncompleteMiddleButton()
}
// Incomplete button
func setupIncompleteMiddleButton() {
// initialize button
middleButton = UIButton(frame: CGRect(x: (self.view.bounds.width / 2) - 25, y: -20, width: 50, height: 50))
middleButton.backgroundColor = UIColor.systemYellow
middleButton.setImage(UIImage(systemName: "sun.max.fill"), for: .normal)
middleButton.imageView?.tintColor = UIColor.white
middleButton.layer.cornerRadius = middleButton.frame.width / 2
middleButton.clipsToBounds = true
self.tabBar.addSubview(middleButton)
middleButton.addTarget(self, action: #selector(self.middleButtonAction), for: .touchUpInside)
self.view.layoutIfNeeded()
}
// Complete button
func setupCompleteMiddleButton() {
// change button color and image
middleButton.backgroundColor = UIColor.systemGreen
middleButton.setImage(UIImage(systemName: "checkmark"), for: .normal)
}
#objc func middleButtonAction(sender: UIButton) {
self.selectedIndex = 1
}
}

UITextField Custom Clear Button

I'm trying to implement custom clear button in text field using the solution on Custom Clear Button
It doesn't work, it shows default clear button. Any idea why? Following is my code:
class CustomTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
let clearButton = UIButton(frame: CGRect(x: 0, y: 0, width: 16, height: 16))
clearButton.setImage(UIImage(named: "Glyph/16x16/Clear")!, for: [])
self.rightView = clearButton
clearButton.addTarget(self, action: #selector(clearClicked), for: .touchUpInside)
self.clearButtonMode = .never
self.rightViewMode = .whileEditing
}
#objc override func clearClicked(sender:UIButton)
{
self.text = ""
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
As mentioned already, in your code the clearClicked method should not override as UITextField doesn't have a clearClicked method to override.
Anyway, I updated the code to work when using it with storyboards. Added the awakeFromNib method which calls the initialisation code.
class CustomTextField: UITextField {
override open func awakeFromNib() {
super.awakeFromNib()
self.initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
func initialize() {
let clearButton = UIButton(frame: CGRect(x: 0, y: 0, width: 16, height: 16))
clearButton.setImage(UIImage(named: "Glyph/16x16/Clear")!, for: [])
self.rightView = clearButton
clearButton.addTarget(self, action: #selector(clearClicked), for: .touchUpInside)
self.clearButtonMode = .never
self.rightViewMode = .whileEditing
}
#objc func clearClicked(sender:UIButton)
{
self.text = ""
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}

Stuck with adding target to button programmatically

I've created a UIButton and I want it to print some message when it's pressed.
So I did something like this:
In loadView()
button.addTarget(self, action: #selector(ViewController.pressButton(button:)), for: .touchUpInside)
A method:
func pressButton(button: UIButton) {
NSLog("pressed!")
}
But nothing happens when I click the button.
Add the button code in your viewDidLoad and it will work for you:
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = UIColor.gray
button.addTarget(self, action: #selector(pressButton(button:)), for: .touchUpInside)
self.view.addSubview(button)
}
func pressButton(button: UIButton) {
NSLog("pressed!")
}
You don´t need to add ViewController.pressButton to selector, it´s enough with the function name.
Swift 4.x version:
let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = .gray
button.tag = 0
button.addTarget(self, action: #selector(pressButton(_:)), for: .touchUpInside)
self.view.addSubview(button)
#objc func pressButton(_ button: UIButton) {
print("Button with tag: \(button.tag) clicked!")
}
Swift 5.1 version:
let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = .gray
button.tag = 100
button.addTarget(self, action: #selector(pressButton), for: .touchUpInside)
self.view.addSubview(button)
#objc func pressButton(button: UIButton) {
print("Button with tag: \(button.tag) clicked!")
}
try this in Swift3!
button.addTarget(self, action: #selector(self.pressButton(button:)), for: .touchUpInside)
#objc func pressButton(button: UIButton) { NSLog("pressed!") }
Use the following code.
button.addTarget(self, action: #selector(FirstViewController.cartButtonHandler), for: .touchUpInside)
Your class name corresponds to FirstViewController
And your selector corresponds to the following function
func cartButtonHandler() {
}
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.
You mention that the addTarget call is in loadView(). Is this in your custom subview, of some kind, or the viewController?
From your selector, it's targeting a method in your ViewController class, but if the target for this action is the view itself, then it would make sense that the action is not going through.
If you declare your button in a viewController, and in viewDidLoad add this target as above, then the message should be printed as you're looking for. I believe you are "targetting" the wrong class with your action.
let cancelButton = UIButton.init(frame: CGRect(x: popUpView.frame.size.width/2, y: popUpView.frame.size.height-20, width: 30, height: 30))
cancelButton.backgroundColor = UIColor.init(patternImage: UIImage(named: cancelImage)!)
cancelButton.addTarget(self, action: #selector(CommentsViewController.canceled), for:.touchUpInside)
Add the button code in override func viewDidLoad() method
Make sure your action handler tagged with #IBAction like this:
#IBAction func pressButton(button: UIButton) {
print("pressed!")
}
Then it will work!

Swift3: Add button with code

Im reading Apples swift (iOS) documentation but its written for Swift 2 and i use Swift 3. I want to add a button programmatically but its seems there is a change and I can't find how to fix it.
Here is the Code for the Swift 2 example:
import UIKit
class RatingControl: UIView {
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Buttons
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
button.backgroundColor = UIColor.red()
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown)
addSubview(button)
}
override func intrinsicContentSize() -> CGSize {
return CGSize(width: 240, height: 44)
}
// MARK: Button Action
func ratingButtonTapped(button: UIButton){
print("Button pressed")
}
}
The only change i made after the 'fix-it' showed the error is this in the selector:
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchDown)
This should have printed "Button pressed" but it doesn't. Any help?
My code:
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .touchDown)
override var intrinsicContentSize : CGSize {
//override func intrinsicContentSize() -> CGSize {
//...
return CGSize(width: 240, height: 44)
}
// MARK: Button Action
func ratingButtonTapped(_ button: UIButton) {
print("Button pressed 👍")
}
Try something like this. I haven't tested but it should work:
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(ratingButtonTapped), for: .touchUpInside)
addSubview(button)
func ratingButtonTapped() {
print("Button pressed")
}
Found the solution. For some reason the:
func ratingButtonTapped(button: UIButton)
needs an "_" before button. So it should be :
func ratingButtonTapped(_ button: UIButton)
And the other part of the code must be :
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .touchDown)
Thanks for helping :) Your method may be correct also but thats the one Apple wants it.

Giving a regular button a bar button identifier in swift

I want to get a button which isn't a bar button item to display the trash bin icon. Does anybody know how to do this programmatically?
Add your action:
func buttonAction(sender:UIButton!)
{
println("Button tapped") // add your button tapped logic here
}
Then inside viewDidLoad:
var image: UIImage = UIImage(named: "Icon")! //Icon = your image name, no need for the extension
let button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton //UIButton type must be CUSTOM or you will get a plain blue system button
button.frame = CGRectMake(100, 100, 100, 50) // Size and Co-ordinates
button.setImage(image, forState: .Normal) //for normal non touched state
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) // "buttonAction" received here
self.view.addSubview(button) //adds subview to display the button
If you need something to easily more around, here is a hacky solution that seems to work. If you need other features from UIButton, this won't be much good.
BarButtonView.swift
import UIKit
class BarButtonView: UIView {
var toolbar = UIToolbar()
var toolbarFrame = CGRect() {
didSet {
display()
}
}
var button = UIBarButtonItem() {
didSet {
display()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
toolbarFrame = frame
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func display() {
toolbar = UIToolbar(frame: toolbarFrame)
toolbar.setBackgroundImage(UIImage(), forToolbarPosition: .Any, barMetrics: .Default)
toolbar.setShadowImage(UIImage(), forToolbarPosition: .Any)
addSubview(toolbar)
let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
toolbar.items = [space, button, space]
}
}
In your view controller:
let button = BarButtonView(frame: CGRect(x: 10, y: 10, width: 40, height: 44))
button.button = UIBarButtonItem(barButtonSystemItem: .Trash, target: self, action: nil)
view.addSubview(button)

Resources