Wednesday, 21 February 2018

Creating Textfield Code - Swift


class HomeViewController: UIViewController, UITextFieldDelegate
{
@IBOutlet var txt_field: UITextField!

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.title = "Home View Controller"
        txt_field = UITextField(frame: CGRect(x: 80, y: 300, width: 200, height: 30))
        txt_field.layer.borderColor = UIColor.blackColor().CGColor
        txt_field.layer.borderWidth = 1.2
        txt_field.placeholder = "Text Me"
        txt_field.textColor = UIColor.brownColor()
        txt_field.textAlignment = NSTextAlignment.Center
        txt_field.delegate = self
        self.view?.addSubview(txt_field);
    }

    func textFieldShouldReturn(textField: UITextField!) -> Bool
    {
        txt_field.resignFirstResponder()
        return true;
    }
   
    //Background Tabs Keyboard is hide
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
    {
        txt_field.resignFirstResponder()
    }
}

Creating Button, Label, TextField & ImageView when Click the Button - Swift

Creating Button, Label, TextField & ImageView when Click the Button - Swift

class HomeViewController: UIViewController, UITextFieldDelegate
{
var btn_navbar:UIButton!
@IBOutlet var lbl_one: UILabel!
var image_View:UIImageView!
@IBOutlet var txt_field: UITextField!

override func viewDidLoad()
    {
        self.title = "Home View Controller"

//Button Code
        btn_navbar = UIButton.buttonWithType(UIButtonType.System) as UIButton
        btn_navbar.frame = CGRect(x: 280, y: 80, width: 40, height: 40)
        btn_navbar.setTitle("Show/Hide", forState: UIControlState())
        btn_navbar.addTarget(self, action: "showhide", forControlEvents: UIControlEvents.TouchUpInside)
        btn_navbar.backgroundColor = UIColor.lightGrayColor()
        self.view.addSubview(btn_navbar)
    }

func showhide()
    {
        if(self.navigationController?.navigationBar.hidden == true)
        {
           self.navigationController?.navigationBar.hidden=false
        }
        else
        {
            self.navigationController?.navigationBar.hidden=true
        }
    }

@IBAction func load_img(sender: AnyObject)
    {
        //Find the Button Tag
        var btn:UIButton=sender as UIButton
        println(btn.tag)
       
        if(btn.tag == 1)
        {
           self.loadImage()
        }
        else if(btn.tag == 2)
        {
            self.loadLabel()
            [self .showTextField()]
        }
    }

//Creating Image View
func loadImage()
    {
        image_View = UIImageView(frame: CGRect(x: 60, y: 500, width: 300, height: 120))
        image_View.image = UIImage(named: "test.jpg");
        image_View.userInteractionEnabled=true
        self.view?.addSubview(image_View)
    }
   
//Creating Label
    func loadLabel()
    {
        lbl_txt=UILabel(frame: CGRect(x: 49, y: 184, width: 224, height: 21))
        lbl_txt.text = "button clicked"
        lbl_txt.textColor = UIColor.orangeColor()
        lbl_txt.textAlignment = NSTextAlignment.Right
    }

//Creating Text Field
func showTextField()
    {
        txt_field = UITextField(frame: CGRect(x: 80, y: 300, width: 200, height: 30))
        txt_field.layer.borderColor = UIColor.blackColor().CGColor
        txt_field.layer.borderWidth = 1.2
        txt_field.placeholder = "Text Me"
        txt_field.textColor = UIColor.brownColor()
        txt_field.textAlignment = NSTextAlignment.Center
        txt_field.delegate = self
        self.view?.addSubview(txt_field);
    }
   
//Return Key is Pressed from Keyboard
    func textFieldShouldReturn(textField: UITextField!) -> Bool
    {
        txt_field.resignFirstResponder()
        return true;
    }
   
    //Background Tabs Keyboard is hide
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
    {
        txt_field.resignFirstResponder()
    }
}

Find the Button Tag - Swift
@IBAction func Btn_Click(sender: AnyObject)
{
//Find the Button Tag
    var btn:UIButton=sender as UIButton
    println(btn.tag)
}

Swift - Navigation Controller

App Delegate
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
var home: HomeViewController = HomeViewController(nibName: "HomeViewController", bundle: nil)
var nav_ctlr: UINavigationController = UINavigationController(rootViewController: home)
self.window.rootViewController = nav_ctlr
self.window.makeKeyAndVisible()
UIApplication.sharedApplication().statusBarHidden = true
return true


View Controller
@IBAction func Landing(sender: AnyObject)   
{
        let land_vc = LandingViewController(nibName:"LandingViewController", bundle:nil)
        self.navigationController?.pushViewController(land_vc, animated: true)
}

Single View Controller Changed to Navigation Controller in Swift

Single View Controller Changed to Navigation Controller in Swift

Step 1: Create a project using Single View Controller as Swift

Step 2: Remove the Main.Storyboard & ViewController

Step 3: Remove the Storyboard column in Info.plist file

Step 4: Create a New File as HomeViewController, Also create a Xib & Language as Swift

Step 5: Add the Codes in AppDelegate.Swift file

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
    {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        self.window!.backgroundColor = UIColor.whiteColor()
       
        // Create a nav/vc pair using the custom ViewController class
        var navigation_controller = UINavigationController()
        let view_controller = HomeViewController(nibName:"HomeViewController", bundle:nil)
       
        // Push the vc onto the nav
        navigation_controller.pushViewController(view_controller, animated: true)
       
        // Set the window’s root view controller
        self.window!.rootViewController = navigation_controller
       
        // Present the window
        self.window!.makeKeyAndVisible()
        return true
    }
}

Get the document path and random document name generate - Swift

Get the document path and random document name generate - Swift

func get_document_path(str_doc_name: String) -> URL {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documents: String = paths[0]
    let docPath:URL = URL(fileURLWithPath: documents).appendingPathComponent(str_doc_name)
    return docPath
}

func generate_doc_name(extension_str: String) -> String {
    let aRandomInt = randomNumber()
    let dateformate = DateFormatter()
    dateformate.dateFormat = "ddMMyyyyHHmmss"
    let date: String = dateformate.string(from: Date())
    let trans_id = "doc-\(date)\(aRandomInt).\(extension_str)"
    return trans_id
}

func randomNumber(range: ClosedRange<Int> = 1000...9999) -> Int {
    let min = range.lowerBound
    let max = range.upperBound
    return Int(arc4random_uniform(UInt32(1 + max - min))) + min
}

Get the Json Values from Text File - Swift

Get the Json Values from Text File - Swift

func get_json_from_txt_file(fileName: String) -> NSDictionary {
    if let path = Bundle.main.path(forResource: fileName, ofType: "txt") {
        do {
            let str_file_contents = try String(contentsOfFile: path, encoding: .utf8)
            let jsonData = str_file_contents.data(using: .utf8)!
            let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! NSDictionary
            return json
        }
        catch {
            print(error)
        }
    }
    let dict = NSDictionary()
    return dict
}

Alert View Controller - Swift

Alert View Controller - Swift

func alertMsg(viewController:UIViewController,title:String,message:String) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle:UIAlertControllerStyle.alert)
    alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    viewController.present(alertController, animated: true, completion: nil)
}

func displayAlertMessage()
{
    let alertController = UIAlertController(title: "Project Name", message: "Image has been uploaded", preferredStyle: .alert)
    let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
        // Code in this block will trigger when OK button tapped.
        print("Ok button tapped");
self.navigationController?.backToViewController(viewController: IncidentObservationVC.self)
    }
    alertController.addAction(OKAction)
    self.present(alertController, animated: true, completion:nil)
}