UIPickerView As InputView For A UITextField In Swift

The Final code for add UIPickerView As InputView For A UITextField

This is very commonly used in many iOS apps. Instead of keyboard popping up when you click on text field, the picker view pops up. You can select strings to be added to the textfield.

//
//  ViewController.swift
//  PickerViewExample
//
//  Created by Ashutosh on 28/06/2018.
//  Copyright © 2018 AppiKate Technologies. All rights reserved.
//

import UIKit


class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var textfield: UITextField!
    var pickerData: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let picker = UIPickerView()
        textfield.inputView = picker
        pickerData = ["Apple", "Mango", "Guava", "Apricot, "Banana", "Blackberry", "Avocado"]
        picker.delegate = self
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }


    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }


    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }


    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        textfield.text = pickerData[row]
    }

}
That’s it! We have successfully played with document directory.
If you like this post, Please comment below or subscribe this blog for latest update.
Leave your comments
Advertisements

Save and Get Image from Document Directory in Swift

Every Apps have its own storage at Document directory. In Document directory user can store audio, video, image, pdf and others files. You can also read and write data of particular apps of Document directory. Document directory store the user data or file at path of apps. In this folder you can create other subfolders, files, and so on. You can read apps data from the path of document directory.
I wrote the code below for swift 4.0

How to Get Document Directory Path

func getDirectoryPath() -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

How to Create Directory

func createDirectory(){
    let fileManager = FileManager.default
    let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("images")
    if !fileManager.fileExists(atPath: paths){
        do {
            try fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print("Couldn't create document directory")
        }
    }else{
        print("Already directory created.")
    }
}

How to Write / Save Image at Document Directory

func saveImageToDocumentDirectory() {
        let fileManager = FileManager.default
        let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("apple.jpg")
        let image = UIImage(named: "apple.jpg")
        let imageData = UIImageJPEGRepresentation(image!, 0.5)
        fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
    }

Read / Get Image from Document Directory

func getImage(imageName : String)-> UIImage{
        let fileManager = FileManager.default
// Here using getDirectoryPath method to get the Directory path
        let imagePath = (self.getDirectoryPath() as NSString).appendingPathComponent(imageName)
        if fileManager.fileExists(atPath: imagePath){
            return UIImage(contentsOfFile: imagePath)!
        }else{
            print("No Image available")
            return UIImage.init(named: "placeholder.png")! // Return placeholder image here
        }
    }

Delete Directory by Name

 func deleteDirectory(directoryName : String){
        let fileManager = FileManager.default
        let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(directoryName)
        if fileManager.fileExists(atPath: paths){
            try! fileManager.removeItem(atPath: paths)
        }else{
            print("Directory not found")
        }
    }
That’s it! We have successfully played with document directory.
If you like this post, Please comment below or subscribe this blog for latest update.
Leave your comments

How to show alert controller in swift

UIAlertController Example in Swift

UIAlertController is introduced in iOS 8  and it supports two styles. Using this you can create an alert dialog like UIAlerview or action sheet like UIActionSheet.

1) SIMPLE ALERT DIALOG

Using the below code you can show alert with without any button

let alert = UIAlertController.init(title: "Alert", message: "Thank you using alert controller", preferredStyle: .alert);
self.present(alert, animated: true, completion: nil)

2) SIMPLE ALERT DIALOG WITH ONE BUTTON

Using the below code you can show alert with one button

let alert = UIAlertController.init(title: "Alert", message: "Thank you using alert controller", preferredStyle: .alert);
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)

3) SIMPLE ALERT DIALOG WITH TWO BUTTONS

Using the below code you can show alert with two buttons with action

let alert = UIAlertController.init(title: "Alert", message: "Thank you using alert controller", preferredStyle: .alert);
alert.addAction(UIAlertAction.init(title: "Delete", style: .default, handler: { (UIAlertAction) in
    //Your Code here
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)

4) CREATE AN ACTION SHEET WITH 2 ACTIONS

Using the below code you can show actionsheet with two buttons with action

let alert = UIAlertController.init(title: "", message: "Choose Image Source", preferredStyle: .actionSheet);
 
alert.addAction(UIAlertAction.init(title: "Take Photo", style: .destructive, handler: { (UIAlertAction) in
 //Your Code here
}))
 
alert.addAction(UIAlertAction.init(title: "Gallery", style: .default, handler: { (UIAlertAction) in
 //Your Code here
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)

5) CREATE AN ALERT DIALOG WITH USERNAME AND PASSWORD FIELDS.

To add a text field you can use the method addTextFieldWithConfigurationHandler.
Text fields can be added to only type UIAlertControllerStyleAlert.

let alert = UIAlertController.init(title: "Alert", message: "Enter Your Login Credentials", preferredStyle: .alert);
alert.addTextField { (textField) in
 textField.placeholder = "Username" //for username
}
alert.addTextField { (textField) in
textField.placeholder = "Password" //for Password
 textField.isSecureTextEntry = true
}
alert.addAction(UIAlertAction.init(title: "Login", style: .default, handler: { (UIAlertAction) in
 //Your Code here
}))
 
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)

You can find Objective C Version here

Reference: Apple Documenation

That’s It. If you like this post, Please comment below or subscribe this blog.

Leave your comments

 

How to get UITableviewCell indexPath by UIButton Click in Swift

Let’s say you’ve subclassed UITableViewCell such that you have added a UIButton as a subview, and whenever you touch that button you want to perform some action on the data source of your UITableView. To do that you probably want to figure out what index path is associated with the pressed button.

Here’s one way, the idea is to add a target and action to the button of the cell for when it’s pressed, and then in that action get the index path by having the table view tell us what index path is associated with the point that was touched.

By Programmatically add target to UIButton

button.addTarget(self, action:#selector(self.buttonClicked:), for: .touchUpInside)

Getting the indexPath when press the button

func buttonClicked(_ sender: UIButton) {

        let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to:self.tableView)

        let indexPath = self.tableView.indexPathForRow(at: buttonPosition)

}

By Storyboard,
You have to create an IBAction with Button.

Now getting the IndexPath

@IBAction func didPressButton(_ sender: UIButton) {

        let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to:self.tableView)

        let indexPath = self.tableView.indexPathForRow(at: buttonPosition)

}

 

I hope it will help anyone. Happy coding.

That’s It. If you like this post, Please comment below or subscribe this blog for latest update.

Leave your comments

How to make UITextField move up when keyboard is present in Swift?

func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(notification: Notification) {
    let info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    let keyboardHeight: CGFloat = keyboardSize.height
    let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
    UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
        self.tableView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
    }, completion: nil)
}
func keyboardWillHide(notification: Notification) {
    let info = notification.userInfo!
    let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
    UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
        self.tableView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }, completion: nil)
}
func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

Leave your comments

How to Create Delegates in Swift

What are delegates?

Delegates are the objects which allow one object to send a message as events happen. Imagine an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action, this can be achieved with the help of delegates!

Delegate == Protocol

Creating a delegate is as simple as creating a protocol — that’s pretty all it is.

protocol CastHandlerDelegate: class {

    /// Media Launched successfully on the cast device
    func launchObjectSuccess()

}

Calling the delegate

To use the delegate we add an optional variable to the class we’ll be sending notifications from.

weak var delegate: CastHandlerDelegate?

We can then call this from anywhere within that class like so:

delegate?.launchObjectSuccess()

Conforming to CastHandlerDelegate

As you probably already know, the next step is to conform to the delegate. First, we tell the class it needs to implement the methods set in the delegate.

class AViewController: UIViewController, CastHandlerDelegate {

}

Next, we implement the methods within our delegate.

class AViewController: UIViewController, CastHandlerDelegate {

    func launchObjectSuccess() {
        print("Media successfully launched!")
    }

}

That’s it! Our delegate has been created and we’re successfully calling the method.

iOS App Icons Sizes

According to Apple’s iOS Human Interface Guidelines, every app must provide an icon to be displayed on a device’s Home screen and in the App Store. An app should specify several different icons of different dimensions to suit different screen sizes and different situations.

iOS_7_Icon_Template
Here are the dimensions for iOS apps:

Name Size(px) Usage
Icon-Small.png 29×29 iPad Settings
Icon-Small@2x.png 58×58 iPhone Settings, iPad Settings for Retina display
Icon-Small@3x.png 87×87 iPhone Settings for Retina display
Icon-40.png 40×40 iPad Spotlight results
Icon-40@2x.png 80×80 iPhone Spotlight results, iPad Spotlight results for retina display
Icon-40@3x.png 120×120 iPhone Spotlight results for retina display
Icon-60@2x.png 120×120 iPhone App Icon
Icon-60@3x.png 180×180 iPhone App Icon for Retina display
Icon-76.png 76×76 iPad App Icon
Icon-76@2x.png 152×152 iPad App Icon for Retina display
Icon-120.png 120×120 CarPlay App Icon
Icon-20@2x.png 40×40 iPhone Notification
Icon-20@3x.png 60×60 iPhone Notification
Icon-20.png 20×20 iPad Notification
Icon-20@2x.png 40×40 iPad Notification
Icon-83@2x.png 167×167 iPad Pro App Icon
iTunesArtwork.png 512×512 App Submission
iTunesArtwork@2x.png 1024×1024 App Submission

That’s It. If you like this post, Please comment below or subscribe this blog for latest update .

Leave your comments