Detecting clicks on a button in Swift - ios

How can I detect clicks on the following UIKit element in Swift, in an Xcode 6 playground?
let testLabel = UILabel(frame: CGRectMake(0, 0, 120, 40))
testLabel.text = "My Button"

The UILabel class is used just to display text on the screen. Sure you can detect taps (not clicks) on it, but theres a UIKit class specifically crafted to handle actions on the screen, and that's UIButton.
Note: A playground is intended for you to test logic, not events, in your code. If you want to play around with iOS specific stuff, try creating a Single View Application Project under the iOS section from Xcode 6.
Implementing a UIButton, assuming you're inside an iOS Project on Xcode:
var button = UIButton(frame: CGRect(x: 0, y: 0, width: 150, height: 60))
button.backgroundColor = UIColor.blackColor()
button.layer.cornerRadius = 3.0
button.setTitle("Tap Me", forState: .Normal)
button.addTarget(self, action: "buttonTapped", forControlEvents: .TouchUpInside)
Then, on the same ViewController class, create the buttonTapped method:
func buttonTapped() {
println("Button tapped!")
}

With Swift 3, UIButton - as a subclass of UIControl - has a method called addTarget(_:action:for:). addTarget(_:action:for:) has the following declaration:
func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents)
Associates a target object and action method with the control.
The Playground code below shows how to detect a click on a button:
import PlaygroundSupport
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// Create button
let button = UIButton(type: UIButtonType.system)
button.setTitle("Click here", for: UIControlState.normal)
// Add action to button
button.addTarget(self, action: #selector(buttonTapped(sender:)), for: UIControlEvents.touchUpInside)
// Add button to controller's view
view.addSubview(button)
// Set Auto layout constraints for button
button.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
let verticalConstraint = button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint])
}
// trigger action when button is touched up
func buttonTapped(sender: UIButton) {
print("Button was tapped")
}
}
// Display controller in Playground's timeline
let vc = ViewController()
PlaygroundPage.current.liveView = vc

Related

Create UIButton on top layer UITableViewController like as AirBnB

How to create UIButton in UITableViewController like as AirBnB map.
Highlighted in red in screenshot.
It's quite easy actually, just create the table view as you always do (either storyboard or code) then create the button, position it correctly, set constraints and make sure it's not a subview of the table view but the view that contains the table view.
Since you didn't specify whether you use the storyboard or not, I did use it for the example below.
See this extremely simple demo I've just created:
This is the view hierarchy:
And these are the constraints for the button:
Create a button first and then then override the function scrollViewDidScroll():
import UIKit
class YourTableViewController: UITableViewController {
private let button = UIButton(type: UIButton.ButtonType.custom) as UIButton
override func viewDidLoad() {
let image = UIImage(named: "Image.png")
button.frame = CGRect(x: yourXpos, y: yourYPos, width: 60, height: 60)
button.setImage(image, for: .normal)
button.clipsToBounds = true
button.layer.cornerRadius = 30
button.addTarget(self, action: #selector(buttonClicked(_:)), for:.touchUpInside)
areaOfTableView.addSubview(button)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = self.areaOfTableView.contentOffset.y
button.frame = CGRect(x: yourXpos, y: offset + yourYpos, width: btn.frame.size.width, height: btn.frame.size.height)
}
#objc private func buttonClicked(_ button: UIButton) {
// Action when you tapped the button
}
}

Dismiss Keyboard from Another View Controller

I'm using SJSegmentedViewController to make my view controller segmented.
I have one view controller named as PlaceReviewsVC where I have added textView for review. For post this review I'm adding Post bar button instance of UIBarButtonItem at navigationItem.rightBarButtonItem in my placeDetailSegmentController which are instance of SJSegmentedViewController.
Now issue is when I click on post button, I'm not able to dismiss keyboard.
I have tried following code to add post button in segmented view controller.
let headerVC = PlaceImagesVC.viewController()
let reviewVC = PlaceReviewsVC.viewController()
reviewVC.delegate = self
reviewVC.title = "Reviews"
let placeDetailSegmentController = SJSegmentedViewController()
placeDetailSegmentController.delegate = self
placeDetailSegmentController.title = "Pedal Studio"
placeDetailSegmentController.headerViewController = headerVC
placeDetailSegmentController.segmentControllers = [reviewVC]
placeDetailSegmentController.headerViewHeight = 280
placeDetailSegmentController.selectedSegmentViewHeight = 2.0
placeDetailSegmentController.selectedSegmentViewColor = .white
let button = UIButton(type: .custom)
button.setImage(#imageLiteral(resourceName: "icon_back").withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.addTarget(self, action:#selector(backButtonTapped), for:.touchUpInside)
button.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
button.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
let leftButton = UIBarButtonItem(customView: button)
placeDetailSegmentController.navigationItem.leftBarButtonItem = leftButton
let btnPost = UIButton(type: .custom)
btnPost.setTitle("POST", for: .normal)
btnPost.addTarget(self, action:#selector(btnPostTapped), for:.touchUpInside)
btnPost.titleLabel?.setFont(Typography.getFont(.PoppinsMedium, size: 12.0), .white)
btnPost.setTitleColor(.menuColor, for: .normal)
btnPost.setTitleColor(.darkGray, for: .highlighted)
btnPost.contentMode = .scaleAspectFit
let rightButton = UIBarButtonItem(customView: btnPost)
placeDetailSegmentController.navigationItem.rightBarButtonItem = rightButton
self.navigationController?.pushViewController(placeDetailSegmentController, animated: true)
where inside btnPostTapped method I have wrote following code to dismiss keyboard. But didn't work.
#objc func btnPostTapped() {
self.view.endEditing(true)
}
How can I dismiss keyboard from one view controller to another?
You should change your code to dismiss keyboard as follows:
#objc func btnPostTapped() {
AppDelegate.shared.window?.endEditing(true)
}
Our app's base is window, So when you perform any event on window it will affect on whole app. I hope this will fix your issue.
Hide keyboard from anywhere
UIApplication.shared.sendAction(#selector(UIApplication.resignFirstResponder), to: nil, from: nil, for: nil)
or
Get the required viewcontroller instance from navigation hierarchy and resign keyboard as:
requiredViewController.textField.resignFirstResponder()
or
requiredViewController.view.endEditing(true)

"Use of unresolved indentifier 'self'" with button.addTarget

I am a beginner to Swift. I have created a very simple button component, but when I try to add a function that is tied to the button click, I get the error: "Use of unresolved identifier 'self.'" Here is my code:
import UIKit
import PlaygroundSupport
let containerView = UIView (frame: CGRect(x: 0, y: 0, width: 600, height: 600))
containerView.backgroundColor = UIColor.blue
let button = UIButton (frame: CGRect(x: 100, y: 100, width: 200, height: 200))
button.backgroundColor = UIColor.yellow
button.setTitle("Test Button", for: .normal)
button.setTitleColor(.red, for: .normal)
button.layer.cornerRadius = 10
func ButtonClicked(_ sender: UIButton) {
print()
}
button.addTarget(self, action: #selector(ButtonClicked), for: .touchUpInside)
containerView.addSubview(button)
PlaygroundPage.current.liveView = containerView
Any help would be appreciated greatly, thanks!
As mentioned in the comments, there is no self to reference in your code as you're not working within a class or struct. The first thing you'll want to do is to wrap this stuff up into a class, and reorganize it a bit. I'd suggest going back to Xcode and doing the following:
File > New > Playground…
Select iOS > Single View
Save this new Playground somewhere.
Now, you should have a simple Playground created from a template. Here, you'll be able to see how a new class called MyViewController that inherits from UIViewController is created. Within that, you'll find a function called loadView(). Then, outside the class, you'll see where this new view controller is created and placed into the PlaygroundPage's current liveView.
Ideally, you should be able to click the Play button at the bottom of the code view, and if the Assistant editor is open, you'll see a simple view with a "Hello World!" label in the center of the view. (The assistant button is the one with the two interlocking circles.)
Assuming that runs and works for you, then I'd suggest you start adding your code back in and try to follow the patterns setup in the template. Place your code that sets up the view in the loadView() function, and move the ButtonClicked() function outside of that, but still within the class.
With a few modifications, you should be able to get up and running, and start playing around with Swift. As an example, here's a working version of your Playground code:
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let containerView = UIView (frame: CGRect(x: 0, y: 0, width: 600, height: 600))
containerView.backgroundColor = UIColor.blue
let button = UIButton (frame: CGRect(x: 100, y: 100, width: 200, height: 200))
button.backgroundColor = UIColor.yellow
button.setTitle("Test Button", for: .normal)
button.setTitleColor(.red, for: .normal)
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(ButtonClicked), for: .touchUpInside)
containerView.addSubview(button)
self.view = containerView
}
#objc func ButtonClicked(_ sender: UIButton) {
print("ButtonClicked")
}
}
PlaygroundPage.current.liveView = MyViewController()
Have fun, spend some quality time with the Swift Programming Guide, and things'll start to make sense soon enough.

Change Color of Programmatically Created Button when Pressed

I'm using a function to create multiple buttons for my game.
func createButton() {
let button = UIButton()
button.setTitle("", for: .normal)
button.frame = CGRect(x:15, y: 50, width: 200, height:100)
button.backgroundColor = UIColor.red
self.view.addSubview(button)
button.addTarget(self, action: Selector(("buttonPressed:")), for:
.touchUpInside)
}
I call this function once for testing in viewDidLoad function, but I don't know what code I should put into my buttonPressed() function for the color of my button to change? I tried doing
self.backgroundColor = UIColor.blue
but that didn't work. I also tried using UIButton and button instead of self, but both of those didn't work either. What should I do?
Your code isn't clean Swift 4 code. Here's how to do this:
Create your button like you are, but change Selector to #selector:
func createButton() {
let button = UIButton()
button.setTitle("", for: .normal)
button.frame = CGRect(x:15, y: 50, width: 200, height:100)
button.backgroundColor = UIColor.red
self.view.addSubview(button)
button.addTarget(self, action: #selector((buttonPressed)), for: .touchUpInside)
}
Use the sender that is automatically added:
#objc func buttonPressed(sender: UIButton) {
sender.backgroundColor = UIColor.blue
}
Additionally may I offer a few suggestions?
Check the background color before changing it. No sense in needlessly changing a button that is already blue.
Since you aren't setting the title to your button, set the tag property (you can even add this as a parameter to createButton). This way you can know which button was tapped.
Just make the button an instance property.
let changingButton = UIButton()
func createButton() {
changingButton.backgroundColor = UIColor.red
changingButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}
#objc func buttonPressed() {
changingButton.backgroundColor = UIColor.blue
}

Eliminate repeated code Swift 3

I have multiple navigation controllers and their root view controllers in my app. I want each navigation bar to have social media buttons closely placed on the right side of the bar. For the same I have used this code to show the buttons in 1 view controller:
let fbImage = UIImage(named: "Facebook.png")!
let twitterImage = UIImage(named: "Twitter.png")!
let youtbImage = UIImage(named:"YouTube.png")!
let fbBtn: UIButton = UIButton(type: .custom)
fbBtn.setImage(fbImage, for: UIControlState.normal)
fbBtn.addTarget(self, action: #selector(HomeViewController.fbBtnPressed), for: UIControlEvents.touchUpInside)
fbBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let fbBarBtn = UIBarButtonItem(customView: fbBtn)
let twitterBtn: UIButton = UIButton(type: .custom)
twitterBtn.setImage(twitterImage, for: UIControlState.normal)
twitterBtn.addTarget(self, action: #selector(HomeViewController.twitterBtnPressed), for: UIControlEvents.touchUpInside)
twitterBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let twitterBarBtn = UIBarButtonItem(customView: twitterBtn)
let youtbBtn: UIButton = UIButton(type: .custom)
youtbBtn.setImage(youtbImage, for: UIControlState.normal)
youtbBtn.addTarget(self, action: #selector(HomeViewController.youtubeBtnPressed), for: UIControlEvents.touchUpInside)
youtbBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let youtbBarBtn = UIBarButtonItem(customView: youtbBtn)
self.navigationItem.setRightBarButtonItems([youtbBarBtn, twitterBarBtn, fbBarBtn], animated: false)
Now I want the same buttons on all navigations bars. I can easily copy this code and respective target methods in viewDidLoad() of each view controller, but too much code is getting repeated. So how can avoid this situation?
I am using Swift 3. I am new to iOS. Any help will be appreciated!
Most duplications are solved by using functions. The first step is to extract that code into a function, the second step is to use the same function from multiple places.
You can add it to an extension, for example:
extension UIViewController {
func addShareButtons() {
...
self.navigationItem.setRightBarButtonItems([youtbBarBtn, twitterBarBtn, fbBarBtn], animated: false)
}
}
and only call
self.addShareButtons()
from every controller that needs the buttons.
You can add button handlers to the extension too.
Another method is to use a UIViewController subclass but that's always a problem if you want to use a UITableViewController subclass.
You can design a custom navigation controller and add these code to the navigation controller. inherit the navigation controller to your storyboard or programmatically where you want to use.
//sample code
class "YourNavigationCorollerName": UINavigationController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
//declare here you code, what you want
}
}
Assuming that these buttons ALWAYS have the same behavior, you can create a custom class for them, and place the repeated code there. For instance:
class FacebookButton : UIButton {
override init() {
super.init()
self.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
self.setImage(UIImage(named: "Facebook.png")!, for: .normal)
}
}
...I think the compiler will yell at you for initializing a UIView without a decoder and frame, but hopefully you get the idea.
To improve on this, you could 1) create a custom UINavigationController with the UIBarButtonItems you want to use, and reuse that controller, and/or 2) create a protocol like the following:
protocol FacebookBtnHandler {
func fbBtnPressed()
}
...and have any relevant VCs conform to it. This would allow you to assign the target and selector for the button in the FacebookButton init method, where you assign the image and frame, and hence prevent repetition of that line, as well.
Try to implement bar button by creating subclass of UIBarButton
class Button: UIBarButtonItem {
convenience init(withImage image : UIImage,Target target: Any, andSelector selector: Any?){
let button = UIButton(type: .custom)
button.setImage(image, for: UIControlState.normal)
button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
button.addTarget(target, action: selector, for: UIControlEvents.touchUpInside)
self.init(customView: button)
}
}
let fbImage = UIImage(named: "Facebook.png")!
let twitterImage = UIImage(named: "Twitter.png")!
let youtbImage = UIImage(named:"YouTube.png")!
let fbBtn = Button(withImage: fbImage, Target: self, andSelector: #selector(HomeViewController.fbBtnPressed))
let twitterBtn = Button(withImage: fbImage, Target: self, andSelector: #selector(HomeViewController.twitterBtnPressed))
let youtubeBtn = Button(withImage: fbImage, Target: self, andSelector: #selector(HomeViewController.youtubeBtnPressed))
self.navigationItem.setRightBarButtonItems([youtbBarBtn, twitterBarBtn, fbBarBtn], animated: false)
and make it for all your view controller
extension UIViewController {
func addButtons() {
// add above code
}
}

Resources