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
    }
}