Search This Blog

Sunday, October 30, 2016

iOS Swift. How to hide back Button Text in UINavigationBar


By default in Navigation Controller the title of back button of current view controller is the title of previous view controller. But what if we want not show any text for back button and show only symbol "<". For that purpose we have to replace in first view controller back button for navigation item.

import UIKit

class ParentViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Remove title from back button. Now only "<" symbol will be show as back button.
        let backButton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        self.navigationItem.backBarButtonItem = backButton
    }

}

Standard "back button"




No text Back Button




Wednesday, October 26, 2016

iOS Swift. UiTableView how to add fixed footer to bottom

If you want to have fixed footer in bottom of view controller which will be not scroll with the table then you can not use UITableViewController. Your view controller must be implemented as UIViewController. Table view and footer view must be added as subviews to root view of view controller. Your view controller must conform to the UITableViewDataSource and UITableViewDelegate protocols.



iOS Swift. How to hide empty cells in UITableView

By default empty space in table view displayed as empty cells.


To make this empty space not displayed as empty cells (rows) we need to set table footer as empty UIView
override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.tableFooterView = UIView()
}

Result


Tuesday, October 25, 2016

XCode 8. How to disable unwanted logs

If you start using new XCode 8 you can see a lot of unwanted logs in console. So for removing this console garbage you need to do the following:

  1. Open XCode Menu > Product > Scheme > Edit scheme...
  2. You need to add Environment Variable "OS_ACTIVITY_MODE" and set its value to disable. 


Monday, October 24, 2016

iOS Swift. How to change color of status bar

First of all for changing style of Status Bar for all controllers in our application we need to add property "View controller-based status bar appearance" to Info.Plist file and set it's value to "NO".



Now for changing style of Status Bar we need to put this code in AppDelegate.Swift file in method didFinishLaunchingWithOptions
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        UIApplication.shared.isStatusBarHidden = false
        UIApplication.shared.statusBarStyle = .lightContent
        
        return true
    }
    
}

Also we can change Status Bar style in Project Setting




Default style of Status bar (Black)



Light style of Status bar (White)




iOS Swift. Change background color of Navigation Bar

In Navigation Bar we can change color for three items:
  1. Background color of Navigation Bar
  2. Color of items in Nvaigation Bar (buttons)
  3. Color of title of Navigation Bar
To change background color of Navigation Bar we will use UIApperance API
All code must be placed in AppDelegate.swift file in method didFinishLaunchingWithOptions
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: 
        [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        // get appearance object
        let navigationAppearance = UINavigationBar.appearance()
        
        // change color of navigation bar background
        navigationAppearance.barTintColor = UIColor.red
        
        // change color of navigation bar items (buttons)
        navigationAppearance.tintColor = UIColor.white
        
        // change color of navigation bar title
        navigationAppearance.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white];
        
        return true
    }
    
}

Results




iOS Swift. How Programmatically go back to previous ViewController


To go back to Root View Controller:
@IBAction func goToFirst(_ sender: AnyObject) {
        let _ = self.navigationController?.popToRootViewController(animated: true)
    }

To go back to previous View Controller:
@IBAction func showPrev(_ sender: AnyObject) {
        let _ = self.navigationController?.popViewController(animated: true)
    }

Wednesday, October 12, 2016

Algorithms. How to check if two words are anagrams (Java)

What is anagram? 
Any word or phrase that exactly reproduces the letters in another order is an anagram. (Wikipedia)
Example of anagrams: DOG, GOD, DGO, GDO, OGD, ODG, 

Task: 
to determine whether two strings anagrams.

Solution: 
1) make both strings similar case - use toLowesrCase() method 
2) Convert each string to char array
3) Use HashMap - for each character in first char array calculate number of repeats. And after that for second char array for each character decrease count of repeats. So if two string are anagrams than we have to get hash map object where for each character we have zero value.


Source code:
import java.util.HashMap;
import java.util.*;

public class Main {

  static boolean isAnagram(String a, String b) {
  
      HashMap<Character, Integer> hash = new HashMap();
      char[] arr1 = a.toLowerCase().toCharArray();
      char[] arr2 = b.toLowerCase().toCharArray();

      for (char c : arr1) {
        int count = 1;
        if (hash.containsKey(c)) {
          count = hash.get(c) + 1;
        }
        hash.put(c, count);
      }

      for (char c : arr2) {
        int count = -1;
        if (hash.containsKey(c)) {
          count = hash.get(c) - 1;
        }
      hash.put(c, count);
      }

      for (char c : hash.keySet()) {
        if (hash.get(c) != 0) {
          return false;
        }
      }

      return true;
  }

  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    String a = scan.next();
    String b = scan.next();
    scan.close();
    boolean ret = isAnagram(a, b);
    System.out.println((ret) ? "Anagrams" : "Not Anagrams");
  }
}



Results:

Test 1:
Hello
olleh
Anagrams

Test 2:
Hello
helll
Not Anagrams

Test 3:
Morning
gninromm
Not Anagrams

Test 4:
Programming
mmggrrpoain
Anagrams

Tuesday, October 11, 2016

iOS Swift. Show two decimal places for Double

We can format output for double values with String Format:
let value = 3.1415
let formatValue = String(format:"%.2f", value) // 3.14

Or we can use NumberFormatter Class (setting min and max number of digits after decimal separator):
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
formatter.roundingMode = NumberFormatter.RoundingMode.halfUp
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
        
let roundedValue1 = formatter.string(from: 0.684) // 0.68
let roundedValue2 = formatter.string(from: 0.687) // 0.69
let roundedValue3 = formatter.string(from: 0.600) // 0.60


iOS Swift. How to check validity of URL in Swift?

There is system method to check validity of URL -  UIApplication.shared.canOpenURL(url as URL)
import Foundation
import UIKit

extension NSURL {
    func verifyUrl () -> Bool {
        //Check for nil
        if let urlString = self.absoluteString {
            // create NSURL instance
            if let url = NSURL(string: urlString) {
                // check if your application can open the NSURL instance
                return UIApplication.shared.canOpenURL(url as URL)
            }
        }
        return false
    }
}

Monday, October 10, 2016

iOS Swift. Rounding a double value to N number of decimal places

For round double values we can use classic algorithm of rounding. Add new function to Double class (with Extension):
import Foundation
import UIKit

extension Double {
    
    func roundToPlaces(places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
    
}

And we can use this extension for double variables:
let pi = 3.14159265
let roundedValue = pi.roundToPlaces(places: 2) // 3.14
print(roundedValue)

How to hide navigation bar for Navigation Controller

If you use Navigation View Controller but want to hide navigation bar you can use following:
override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.setNavigationBarHidden(true, animated: false)
}

iOS Swift. How to hide the status bar

For hide status bar you must override method prefersStatusBarHidden  in each View Controller you need.
override var prefersStatusBarHidden: Bool {
        return true
}

iOS Swift. How to show Date in local Time Zone

For showing date in local time zone we need to use DateFormatter class and set to it our local time zone:
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
        
let localTZ = TimeZone.current
dateFormatter.timeZone = localTZ
print(localTZ.abbreviation())
        
self.userLastTimeRefreshedLabel.text = String("\(dateFormatter.string(from: date))")

Sunday, October 9, 2016

iOS Swift. How to convert a string with comma to a string with decimal


When you need to convert string to double or float value there might be a problem with separator inside string (comma or dot). For converting your string to number you can use NumberFormatter. You just need to specify the decimal separator:
import Foundation
import UIKit

extension String {
    
    var convertCommaToDecimal: Double {
        let numberFormatter = NumberFormatter()
        numberFormatter.decimalSeparator = "."
        if let result = numberFormatter.number(from: self) {
            return result.doubleValue
        } else {
            numberFormatter.decimalSeparator = ","
            if let result = numberFormatter.number(from: self) {
                return result.doubleValue
            }
        }
        return 0
    }
    
}

And the result
"3.57".convertCommaToDecimal // 3.57
"3,57".convertCommaToDecimal // 3.57

iOS Swift. How to trim whitespace in a string

In Swift we can trim from string all symbols that we want. If we want to remove white spaces and new lines, we need to use following:
let str = "  Hello World  "
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
This string will be trimmed to "Hello World"

For more handy using we can write extension for String class
import Foundation
import UIKit

extension String {
    
    func trim() -> String {
        return self.trimmingCharacters(in: CharacterSet.whitespaces)
    }
    
}

And here we use this extension

let result = " Hello World ".trim()
print(result)
// "Hello World"