Programming on iOS

 

[iOS]Sending UIView to Back or Front

[日本語]

 

I will introduce how to change stacking order of UIView as below picture.

 

Environment : Xcode 8.3, Swift 3

 

In the case of iOS, use sendSubView(toBack:) for sending UIView to back and use bringSubView(toFront:) for sending UIView to front.

 

Example

import UIKit

 

class ViewController: UIViewController {

  let label1:UILabel = UILabel();

  let label2:UILabel = UILabel();

  let button1:UIButton = UIButton();

  let button2:UIButton = UIButton();

 

  override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

    label1.frame = CGRect(x: 0, y: 0, width: 300, height: 300)

    label1.text = "Label1"

    label1.backgroundColor = UIColor.blue self.view.addSubview(label1)

 

    label2.frame = CGRect(x: 50, y: 50, width: 300, height: 300)

    label2.text = "Label2"

    label2.backgroundColor = UIColor.yellow

    self.view.addSubview(label2)

 

    button1.frame = CGRect(x: 0, y: 400, width: 200, height: 50)

    button1.backgroundColor = UIColor.blue

    button1.setTitle("Send Label1 to Back", for: .normal)

    button1.addTarget(self, action: #selector(self.touchUpButton1), for: .touchUpInside)

    self.view.addSubview(button1)

 

    button2.frame = CGRect(x: 210, y: 400, width: 200, height: 50)

    button2.backgroundColor = UIColor.red

    button2.setTitle("Send Label1 to Front", for: .normal)

    button2.addTarget(self, action: #selector(self.touchUpButton2), for: .touchUpInside) self.view.addSubview(button2)

  }

 

  override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

  }

 

  func touchUpButton1(){

   //To Back

   self.view.sendSubview(toBack: label1)

  }

 

  func touchUpButton2(){

   //To Front self.view.bringSubview(toFront: label1)

  }

}

[iOS]Color gradation and rounding corners

[日本語]

 

I will introduce how to set gradation on a background color of View and round corners of View on iOS.

 

Environment:Xcode 8, Swift 3

 

Use CAGradientLayer to set color gradation to UIView on iOS.

Set gradient colors to CAGradientLayer's colors method and set gradation direction using startPoint and endPoint of CAGradientLayer.

At last, set CAGradientLayer to UIView's layer using insertSublayer.

let buttonSample:UIButton = UIButton()

let gradientLayer = CAGradientLayer()

gradientLayer.frame = buttonSample.bounds

let color1:CGColor = UIColor.blue.cgColor

let color2:CGColor = UIColor.white.cgColor

gradientLayer.colors = [color1, color2]

gradientLayer.startPoint = CGPoint(x: 0, y: 0)

gradientLayer.endPoint = CGPoint(x: 1, y: 1)

buttonSample.layer.insertSublayer(gradientLayer, at: 0)

 

Use cornerRadius of UIView's CALayer for rounding corners of UIView.

buttonSample.layer.cornerRadius = 5

 

[Sample Code]

import UIKit

 

class ViewController: UIViewController {

  let buttonSample:UIButton = UIButton();

 

  override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

    buttonSample.frame = CGRect(x: 10, y: 10, width: 100, height: 50)

    buttonSample.setTitle("Sample", for: .normal)

    let gradientLayer = CAGradientLayer()

    gradientLayer.frame = buttonSample.bounds

    let color1:CGColor = UIColor.blue.cgColor

    let color2:CGColor = UIColor.white.cgColor

    gradientLayer.colors = [color1, color2]

    gradientLayer.startPoint = CGPoint(x: 0, y: 0)

    gradientLayer.endPoint = CGPoint(x: 1, y: 1)

    buttonSample.layer.insertSublayer(gradientLayer, at: 0)

    buttonSample.layer.cornerRadius = 5

    self.view.addSubview(buttonSample)

  }

 

  override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

  }

}

[iOS]How to capture screen

[日本語]

 

I introduce how to capture screen and make a bitmap image on iOS this time.

 

Environment:Xcode 8.3, Swift 3

 

Sample code is below.

import UIKit

 

class ViewController: UIViewController {

  let label1:UILabel = UILabel()

  let imageView1:UIImageView = UIImageView()

  let button1:UIButton = UIButton()

 

  override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

    label1.frame = CGRect(x: 10, y: 20, width: 100, height: 100)

    label1.text = "Label1"

    label1.backgroundColor = UIColor.blue

    self.view.addSubview(label1)

 

    imageView1.frame = CGRect(x: 10, y: 125, width: 300, height: 300)

    imageView1.layer.borderWidth = 0.5

    imageView1.contentMode = .scaleAspectFit

    self.view.addSubview(imageView1)

 

    button1.frame = CGRect(x: 10, y: 430, width: 100, height: 50)

    button1.backgroundColor = UIColor.blue

    button1.layer.cornerRadius = 5

    button1.setTitle("Button1", for: .normal)

    button1.addTarget(self, action: #selector(self.touchUpButton1), for: .touchUpInside)

    self.view.addSubview(button1)

  }

 

  override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

  }

 

  func touchUpButton1(){

    //Get context

    let rect = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)

    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)

    let context: CGContext = UIGraphicsGetCurrentContext()!

 

    //Write screen's objects' info at context

    self.view.layer.render(in: context)

 

    //Get UIImage

    let capturedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!

 

    //Close context

    UIGraphicsEndImageContext()

    imageView1.image = capturedImage

  }

}

At first, use UIGraphicsBeginImageContextWithOptions, and make context of bitmap for capturing screen.

And write screen's objects' info at context.("self.view.layer.render(in:context)")

 

And use UIGraphicsGetImageFromCurrentImageContext, and get UIImage from context.

At last, use UIGraphicsEndImageContext, and close context.

[iOS]Core Data Programming

[日本語]

 

You can do database programming by Core Data, O/R mapping tool for Sqlite, on iOS.

 

Environment: Xcode 8.3, Swift 3

 

1.Preparation

At first, Check "Use Core Data" when project is created.

And code of Core Data Objects are created in AppDelegate.

 

Next, select "[project name].xcdatamodeld" and define table layout.

 

To save UIImage, select "Binary Data" in Type and check "Allow External Storage". 

When the size of UIImage is big, URL of UIImage is saved in Core Data.

When you don't check "Allow External Storage", the time of saving core data will take and memory utilization will be increase instantly, and an application will crash.

 

After table layout definition, execute [Editor]-[Create NSManagedObject Subclass] on Xcode.

And class of table layout definition, NSManagedObject is created.

 

At last, declare "import Core Data" at the top of class using Core Data.

 

2.How to INSERT

At first, Make NSManagedObjectContext in AppDelegate.

Next, Make NSManagedObject from NSManagedObjectContext.

Let's see code for inserting new data by Core Data.

import UIKit

import CoreData

 

class ViewController: UIViewController {  

 

 private var imageView:Array<UIImageView!> = Array<UIImageView!>() 

 

 func saveImageData(){

  

  //Save UIImageView's image  

  let imageData:NSData! = UIImageJPEGRepresentation(imageView[0].image,1.0)!

  

  var imageOrientation:Int = 0   

  if (imageView[0].image.imageOrientation == UIImageOrientation.Down){    

   imageOrientation = 2   

  }else{    

   imageOrientation = 1   

  }   

 

  let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate   

  let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext   

  let objectEntity:NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Object", inManagedObjectContext: managedContext) as NSManagedObject

  

  objectEntity.setValue(imageData, forKey: "dataValue")   

  objectEntity.setValue(imageOrientation, forKey: "imageOrientation")   

 

  do {    

   try managedContext.save()   

  }catch let error{    

   NSLog("\(error)")   

  }   

  managedContext.reset()  

 }

}

 

2.How to SELECT

Let's see code for selecting data by Core Data.

func LoadData(id:String){

 var minX:CGFloat = 0

 var minY:CGFloat = 0

 var widthValue:CGFloat = 0

 var heightValue:CGFloat = 0

 var imageOrientation:Int = 0

  

 let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate   

 let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext

  

 let fetchRequest = NSFetchRequest(entityName: "Object")   

 fetchRequest.returnsObjectsAsFaults = false   

 

 let predicate = NSPredicate(format: "id == %@", id)   

 fetchRequest.predicate = predicate   

 

 let descriptor_1 = NSSortDescriptor(key: "objectType", ascending: true)   

 let descriptor_2 = NSSortDescriptor(key: "createDateTime", ascending: false)   

 fetchRequest.sortDescriptors = [descriptor_1,descriptor_2]

 

 do {     

  let fetchResults: Array = try managedContext.executeFetchRequest(fetchRequest)      

 

  for fetchResult in fetchResults {       

   let object = fetchResult as! NSManagedObject

      

   width = fetchResult.valueForKey("width") as! CGFloat       

   height = fetchResult.valueForKey("height") as! CGFloat       

   minX = fetchResult.valueForKey("minX") as! CGFloat       

   minY = fetchResult.valueForKey("minY") as! CGFloat       

   data = fetchResult.valueForKey("data") as! NSData

      

   image = UIImage(data: data)       

   imageOrientation = fetchResult.valueForKey("imageOrientation") as! Int       

   if (imageOrientation == 2) {         

    image = UIImage(CGImage: image!.CGImage!, scale: image!.scale, orientation: UIImageOrientation.Down)       

   }

 

   imageView.append(UIImageView())             

   imageView[imageView.count - 1].frame = CGRect(x:minX,y:minY,width:widthValue,height:heightValue)       

   imageView[imageView.count - 1].image = image       

   self.view.addSubView(imageView[imageView.count-1])      

  }   

 }catch let error{       

  NSLog("\(error)")   

 }   

 managedContext.reset()  

}

Use NSPredicate for designating searching options.

Use NSSortDescriptor and ascending option for designation sort options.

 

If you road UIImage, check UIImageOrientation.

If UIImageOrientation is down, you must invert UIImage.

 

3.How to UPDATE

Update value of data which is read.

Let's see code for updating data by Core Data.

func UpdateData(id:String, objectType:Int){

    var index:Int = 0

  

 let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate   

 let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext   

 

 let fetchRequest = NSFetchRequest(entityName: "Object")   

 fetchRequest.returnsObjectsAsFaults = false   

 

 let predicate = NSPredicate(format: "id == %@ And objectType == %d", id, objectType)   

 fetchRequest.predicate = predicate   

 

 do {    

  let fetchResults: Array = try managedContext.executeFetchRequest(fetchRequest)     

 

  for fetchResult in fetchResults {      

   let object = fetchResult as! NSManagedObject

 

   //Get value

   index = fetchResult.valueForKey("index") as! Int      

 

   //Update value     

   object.setValue(imageView[index].frame.width, forKey: "width")      

   object.setValue(imageView[index].frame.height, forKey: "height")      

   object.setValue(imageView[index].frame.minX, forKey: "minX")      

   object.setValue(imageView[index].frame.minY, forKey: "minY")      

 

   let imageData:NSData! = UIImageJPEGRepresentation(imageView[index].image,1.0)!      

   object.setValue(imgeData, forKey: "data")

 

   var imageOrientation:Int = 0   

   if (imageView[index].image.imageOrientation == UIImageOrientation.Down){    

    imageOrientation = 2   

   }else{    

    imageOrientation = 1   

   }

   object.setValue(imageOrientation, forKey:"imageOrientation")  

  }     

  try managedContext.save()   

 }catch let error{    

  NSLog("\(error)")   

 }  

 managedContext.reset()  

}

 

4.How to DELETE

Delete data which is read.

func DeleteData(id:String,objectType:Int){   

 let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate   

 let managedContext: NSManagedObjectContext! = appDelegate.managedObjectContext

  

 let fetchRequest = NSFetchRequest(entityName: "Object")   

 fetchRequest.returnsObjectsAsFaults = false   

 

 let predicate = NSPredicate(format: "id == %@ and objectNo == %d", id,objectType)   

 fetchRequest.predicate = predicate  

 

 do {   

  var fetchResults: Array! = try managedContext.executeFetchRequest(fetchRequest)   

  for fetchResult in fetchResults {    

   let object = fetchResult as! NSManagedObject    

 

   //Making a mark as deleted   

   managedContext.deleteObject(object)   

  }

        //Exec saving -> Delete data

  try managedContext.save()  

 }catch let error{    

  NSLog("\(error)")   

 }   

 managedContext.reset()  

}