Search This Blog

Showing posts with label UiKit. Show all posts
Showing posts with label UiKit. Show all posts

Friday, February 9, 2018

iOS Swift. Difference between leftAnchor and leadingAnchor

When we working with constraint programatically we can have two options for left side: leadingAnchor and leftAnchor, the same for right side: rightAnchor and trailingAnchor.

What is the difference between this anchors?

for left side
self.view.leftAnchor
and
self.view.leadingAnchor

for right side:
self.view.rightAnchor
and
self.view.trailingAnchor

leftAnchor and rightAnchor are strongly fixed and always depend on the left and right sides of the screen. leadingAnchor and trailingAnchor are flexible and depend on the device locale. For locales, where the spelling is from left to right this anchors can be used interchangeably(left with leading and right with trailing). For locales, where the spelling is from right to left leadingAnchor will depend on the right side and trailingAnchor will depend the left side.

For example, you have a screen on which the label is located on the left and textfield on the right for the locale where the writing is from left to right. For a locale where the spelling is from right to left label will be located right and textfield on the left.

You should always use leadingAnchor and trailingAnchor instead of leftAnchor and rightAnchor unless you have special requirements that say that the interface elements are always depend on the left or on the right.

If you want the interface element to be on the screen on the left or right depending on the locale, then use leadingAnchor and trailingAnchor, respectively.

If you want the interface element to always be located on the left or right, regardless of the locale, then use leftAnchor and rightAnchor , respectively.

Sunday, January 28, 2018

iOS Swift. How to Asynchronously Download and Cache Images

Loading an Image Asynchronously


Download image from Internet using URLSession and its dataTask method. Image will be loaded asynchronously and set as image of  UIImageView in main UI thread using DispatchQueue.main.async.
import UIKit

class SingleImageViewController: UIViewController {
    
    @IBOutlet var imageView: UIImageView!
    
    let urlStr = "https://cdn.pixabay.com/photo/2017/05/07/08/56/pancakes-2291908_960_720.jpg"

    override func viewDidLoad() {
        super.viewDidLoad()
        
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        
        if let url = URL(string: urlStr) {
            let session = URLSession.shared
            let dataTask = session.dataTask(with: url) { (data, response, error) in
                if let unwrappedError = error {
                    print(unwrappedError)
                    return
                }
                
                if let unwrappedData = data {
                    let image = UIImage(data: unwrappedData)
                    DispatchQueue.main.async(execute: {
                        self.imageView.image = image
                    })
                }
                
            }
            dataTask.resume()
        }
    }

}

Display downloaded image


Saturday, November 11, 2017

iOS Swift. How to create background view for status bar

Here I show you how to create custom background view for status bar. For demo example let create App with Navigation Controller and custom background color of Navigation bar. Code for that provided below. We will put it inside didFinishLaunchingWithOptions method.

func application(_ application: UIApplication, 
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
    UINavigationBar.appearance().barTintColor = UIColor(red: CGFloat(68.0/255.0),
                                                        green: CGFloat(151.0/255.0),
                                                        blue: CGFloat(227.0/255.0),
                                                        alpha: 1.0)
    
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.makeKeyAndVisible()
    let vc = ViewController()
    vc.view.backgroundColor = UIColor.white
    vc.title = "Custom Status Bar"
    self.window?.rootViewController = UINavigationController(rootViewController: vc)
}

This is how it looks.


Now we have blue color of navigation bar. It will be good to change status bar text color to white. We can do it by changing Info.plist file and set property 
View controller-based status bar appearance to NO


Make status bar text color white we can with settings in App Targets.


Or programmatically in didFinishLaunchingWithOptions method.
UIApplication.shared.statusBarStyle = .lightContent

Now we have white color of status bar text.


Let's go further. Now we need custom background color for status bar. For this purpose let's create special view and add it as subview to our window. Also we must provide couple of constraints.
let statusBarBackgroundView = UIView()
statusBarBackgroundView.translatesAutoresizingMaskIntoConstraints = false
statusBarBackgroundView.backgroundColor = UIColor(red: CGFloat(54.0/255.0),
                                                      green: CGFloat(120.0/255.0),
                                                      blue: CGFloat(181.0/255.0),
                                                      alpha: 1.0)
self.window?.addSubview(statusBarBackgroundView)
self.window?.addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "V:|[b(20)]",
                                       options: NSLayoutFormatOptions(),
                                       metrics: nil,
                                       views: ["b" : statusBarBackgroundView]))
self.window?.addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "H:|[b]|",
                                       options: NSLayoutFormatOptions(),
                                       metrics: nil,
                                       views: ["b" : statusBarBackgroundView]))

Here is result.


Full Code
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        UINavigationBar.appearance().barTintColor = UIColor(red: CGFloat(68.0/255.0),
                                                            green: CGFloat(151.0/255.0),
                                                            blue: CGFloat(227.0/255.0),
                                                            alpha: 1.0)
        
        UIApplication.shared.statusBarStyle = .lightContent
    
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.makeKeyAndVisible()
        let vc = ViewController()
        vc.view.backgroundColor = UIColor.white
        vc.title = "Custom Status Bar"
        self.window?.rootViewController = UINavigationController(rootViewController: vc)
        
        let statusBarBackgroundView = UIView()
        statusBarBackgroundView.translatesAutoresizingMaskIntoConstraints = false
        statusBarBackgroundView.backgroundColor = UIColor(red: CGFloat(54.0/255.0),
                                                          green: CGFloat(120.0/255.0),
                                                          blue: CGFloat(181.0/255.0),
                                                          alpha: 1.0)
        self.window?.addSubview(statusBarBackgroundView)
        self.window?.addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "V:|[b(20)]",
                                           options: NSLayoutFormatOptions(),
                                           metrics: nil,
                                           views: ["b" : statusBarBackgroundView]))
        self.window?.addConstraints(
            NSLayoutConstraint.constraints(withVisualFormat: "H:|[b]|",
                                           options: NSLayoutFormatOptions(),
                                           metrics: nil,
                                           views: ["b" : statusBarBackgroundView]))
        
        return true
    }
}

Ways to create NSLayoutConstraint

There are a lot of ways to work with AutoLayout and Constraints. You can specify constraints using different techniques. Here I enumerate methods that I know:
  1. Using UIBuilder and Storyboard
  2. Using code and constraint method
  3. Using code and NSLayoutConstraint constructor
  4. Create Constraints with Visual Format 
  5. Using Framework - SnapKit
We will make simple task - create view of size: width 240, height 128, and center it vertically and horizontally.

1. Using UIBuilder


Adding width and height constraints


Align center vertically and horizontally

There are 4 constraints 

Result


2. Using code - way 1 - constraint method


Activate each constraint separately.
override func viewDidLoad() {
    super.viewDidLoad()
        
    let customView = UIView()
    customView.backgroundColor = UIColor.lightGray
    // 1. Add your view as subview
    self.view.addSubview(customView)
    // 2. Activate AutoLayout
    customView.translatesAutoresizingMaskIntoConstraints = false
    // 3. Activate Constraints
    customView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
    customView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    customView.widthAnchor.constraint(equalToConstant: 240).isActive = true
    customView.heightAnchor.constraint(equalToConstant: 128).isActive = true
}

Or it can be done differently - activate all constraints together.
NSLayoutConstraint.activate([
    customView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
    customView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
    customView.widthAnchor.constraint(equalToConstant: 240),
    customView.heightAnchor.constraint(equalToConstant: 128)
 ])

3. Using code - way 2 - NSLayoutConstraint constructor


Another way to create NSLayoutConstraint
let centerXConstraint = NSLayoutConstraint(item: customView,
                                                   attribute: .centerX,
                                                   relatedBy: .equal,
                                                   toItem: self.view,
                                                   attribute: .centerX,
                                                   multiplier: 1,
                                                   constant: 0)
let centerYConstraint = NSLayoutConstraint(item: customView,
                                                   attribute: .centerY,
                                                   relatedBy: .equal,
                                                   toItem: self.view,
                                                   attribute: .centerY,
                                                   multiplier: 1,
                                                   constant: 0)
let widthConstraint = NSLayoutConstraint(item: customView,
                                                   attribute: .width,
                                                   relatedBy: .equal,
                                                   toItem: nil,
                                                   attribute: .notAnAttribute,
                                                   multiplier: 1,
                                                   constant: 240)
let heightConstraint = NSLayoutConstraint(item: customView,
                                                   attribute: .height,
                                                   relatedBy: .equal,
                                                   toItem: nil,
                                                   attribute: .notAnAttribute,
                                                   multiplier: 1,
                                                   constant: 128)

NSLayoutConstraint.activate([centerXConstraint, centerYConstraint, widthConstraint, heightConstraint])

Or, for activation of constraints, instead of NSLayoutConstraint.activate() we can use method of parent view addConstraints
self.view.addConstraints([centerXConstraint, centerYConstraint, widthConstraint, heightConstraint])

4. Create Constraints with Visual Format 

There is one more way to create constraints. It is called Visual Format. For creating constraint you must provide description of it with special syntax. V for Vertical constraints, H for Horizontal.
self.view.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "V:[customView(128)]",
            options: NSLayoutFormatOptions(),
            metrics: nil,
            views: ["customView": customView]))
self.view.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "H:[customView(240)]",
            options: NSLayoutFormatOptions(),
            metrics: nil,
            views: ["customView": customView]))
self.view.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "V:[superView]-(<=1)-[customView]",
            options: NSLayoutFormatOptions.alignAllCenterX,
            metrics: nil,
            views: ["customView": customView, "superView": self.view]))
self.view.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "H:[superView]-(<=1)-[customView]",
            options: NSLayoutFormatOptions.alignAllCenterY,
            metrics: nil,
            views: ["customView": customView, "superView": self.view]))

5. Using Framework - SnapKit

NSLayoutConstraints as Apple provide it is not most handy thing. So there is a framework which simplify creation of constraints.

You can get it here - SnapKit Framework

import SnapKit

let customView = UIView()
customView.backgroundColor = UIColor.lightGray
self.view.addSubview(customView)
customView.snp.makeConstraints { (maker) in
    maker.width.equalTo(240)
    maker.height.equalTo(128)
    maker.centerX.equalTo(self.view)
    maker.centerY.equalTo(self.view)
}

Friday, November 10, 2017

iOS Swift. How to create app without storyboard

There is a question: Is it possible to create iOS application . without using Storyboard?. Answer is Yes, it is possible. For implementing this we must create our custom UIWindow and set root controller for it. In code below I show how to do this.

AppDelegate class and didFinishLaunchingWithOptions method

In AppDelegate class method didFinishLaunchingWithOptions we create UIWindow and set root controller for it.
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.makeKeyAndVisible()
        
        let viewController = ViewController()
        let navigationController = UINavigationController(rootViewController: viewController)
        self.window?.rootViewController = navigationController
        
        return true
    }
}

ViewController

Our ViewController. We set title and add button to center of it using constraints.
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "No Storyboard"
        self.view.backgroundColor = UIColor.white
        
        let button =  UIButton(type: .system)
        button.setTitle("Success", for: .normal)
        self.view.addSubview(button)
        
        button.translatesAutoresizingMaskIntoConstraints = false
        button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
        button.widthAnchor.constraint(equalToConstant: 200).isActive = true
        button.heightAnchor.constraint(equalToConstant: 50).isActive = true
    }
}

Result


Monday, October 30, 2017

iOS Swift. Swipe gesture recogniser in multiple directions

For swiping in each direction we need to create Swipe gesture recognizer and specify direction that we need for this recognizer. For each direction we need create separate recognizer.
override func viewDidLoad() {
    super.viewDidLoad()
        
    // Swipe Left
    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swipingLeft))
    swipeLeft.direction = .left
    self.view.addGestureRecognizer(swipeLeft)
        
    // Swipe Right
    let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipingRight))
    swipeRight.direction = .right
    self.view.addGestureRecognizer(swipeRight)
}
    
@objc func swipingLeft(sender: UISwipeGestureRecognizer) {
    print("Swipe Left")
}
    
@objc func swipingRight(sender: UISwipeGestureRecognizer) {
    print("Swipe Right")
}

We can make code more universal. When we swiping in different directions we can handle all this swipes in one method and switch between directions.
override func viewDidLoad() {
    super.viewDidLoad()
        
    let swipeRight = UISwipeGestureRecognizer(target: self,
                                              action: #selector(self.handleSwipe))
    swipeRight.direction = UISwipeGestureRecognizerDirection.right
    self.view.addGestureRecognizer(swipeRight)
        
    let swipeDown = UISwipeGestureRecognizer(target: self,
                                             action: #selector(self.handleSwipe))
    swipeDown.direction = UISwipeGestureRecognizerDirection.down
    self.view.addGestureRecognizer(swipeDown)
}
    
@objc func handleSwipe(gesture: UIGestureRecognizer) {
    if let swipeGesture = gesture as? UISwipeGestureRecognizer {
        switch swipeGesture.direction {
        case UISwipeGestureRecognizerDirection.right:
            print("Swiped right")
        case UISwipeGestureRecognizerDirection.down:
            print("Swiped down")
        case UISwipeGestureRecognizerDirection.left:
            print("Swiped left")
        case UISwipeGestureRecognizerDirection.up:
            print("Swiped up")
         default:
            break
        }
    }
}

Sunday, October 29, 2017

How to add a border just to the one side of a UIView

We need to add border to UIView. Let's create view and place it in the center of screen with NSLayoutConstraint
var containerView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.containerView = UIView()
    self.containerView.backgroundColor = UIColor.red
    self.view.addSubview(containerView)
    self.containerView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        self.containerView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
        self.containerView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        self.containerView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.3),
        self.containerView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.3)
    ])
}


Border using SubView


In viewDidAppear method add top border to view using addSubView method.
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let topBorderView = UIView(frame: CGRect(x: 0, y: 0,
                                                 width: self.containerView.frame.size.width,
                                                 height: 10))
    topBorderView.backgroundColor = UIColor.black
    self.containerView.addSubview(topBorderView)
}
Great, top border is added. But is it adaptive, what happen when parent view frame is changed. Let's see.


When parent view frame changed top border is not changed it's size.



Monday, October 23, 2017

iOS Swift. How to Animate a Bar Button Item

Today I will show you how to make animated bar buttons and make it with coding. First of all we need icons for our navigation bar. Let's get them from google material design icons.

Google Material Design Icons

Adding icons to project


The only thing that we make with Storyboard is embed our view controller in navigation controller. We need it for navigation bar as container for bar buttons.


Declare two bar button items
var settingsBarButton: UIBarButtonItem?
    
var favoriteBarButton: UIBarButtonItem?

And Bool variable for switch icon of favourite button.
var favorite: Bool = false

Creating images from Assets. One image for settings icon and two images for favourite icon (favourite and unfavourite).
let settingsImage = UIImage(named: "ic_settings_48pt")?.withRenderingMode(.alwaysTemplate)
let favoriteBorderImage = UIImage(named: "ic_favorite_border_48pt")?.withRenderingMode(.alwaysTemplate)
let favoriteFullImage = UIImage(named: "ic_favorite_48pt")?.withRenderingMode(.alwaysTemplate)

Inside viewDidLoad method let's create UIButton, configure it and initialize settings bar button item with this UIButton. We put it to the left part of navigation item of view controller.
let settingsButton = UIButton(type: .system)
settingsButton.tintColor = .black
settingsButton.setImage(self.settingsImage, for: .normal)
settingsButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
settingsButton.addTarget(self, action: #selector(settingsButtonTapped), for: .touchUpInside)
self.settingsBarButton = UIBarButtonItem(customView: settingsButton)
self.navigationItem.setLeftBarButton(settingsBarButton, animated: false)

It is touch handler for button. Here we make animation. There are two steps:

  1. Rotate view to some angle
  2. With animation we restore initial view rotation as it was before first rotation

@objc func settingsButtonTapped(_ sender: UIButton) {
    self.settingsBarButton?.customView?.transform =
        CGAffineTransform(rotationAngle: CGFloat(CGFloat.pi * -3/4))
    UIView.animate(withDuration: 0.8) {
        self.settingsBarButton?.customView?.transform = .identity
    }
}

The same for favourite bar button. Initially we create it with favourite empty icon (unfavourite). We put it to the right part of navigation item of view controller.
let favoriteButton = UIButton(type: .system)
favoriteButton.tintColor = .black
favoriteButton.setImage(self.favoriteBorderImage, for: .normal)
favoriteButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
favoriteButton.addTarget(self, action: #selector(favoriteButtonTapped), for: .touchUpInside)
self.favoriteBarButton = UIBarButtonItem(customView: favoriteButton)
self.navigationItem.setRightBarButton(favoriteBarButton, animated: false)

Touch handler for favourite button. The same logic as before, but here we use other type of transformation(previously we use rotation), now we use scaling transformation:
  1. Change button scale.
  2. Restore button scale with animation. Also inside animation we change icon of button. 
Here we use spring animation. It means that here will be appear special effects during animations. Such as velocity and damping changing and etc.
@objc func favoriteButtonTapped(_ sender: UIButton) {
        self.favoriteBarButton?.customView?.transform = CGAffineTransform(scaleX: 0, y: 0)
        UIView.animate(withDuration: 0.5,
                       delay: 0.0,
                       usingSpringWithDamping: 0.6,
                       initialSpringVelocity: 10,
                       options: .curveEaseInOut,
                       animations: {
                        self.favorite = !self.favorite
                        let image = self.favorite ? self.favoriteFullImage : self.favoriteBorderImage
                        if let button = self.favoriteBarButton?.customView as? UIButton {
                            button.setImage(image, for: .normal)
                        }
                        self.favoriteBarButton?.customView?.transform = .identity
        }, completion: nil)
}

How it all work





GitHub Link