Skip to main content

Tìm hiểu về CALayer trong iOS


Như bạn đã biết, mọi thứ mà bạn nhìn thấy trong ứng dụng iOS là một view. Nó có thể là button view, table view, slide view, và thậm chí là parent view (chứa nhiều view con khác). Tuy nhiên bạn có thể không biết rằng mỗi view trong iOS lại dựa trên một lớp khác gọi là layer - cụ thể là CALayer. Trong bài viết này bạn sẽ biết về CALayer và cách thức mà CALayer hoạt động. Bạn cũng có thể tìm thấy các ví dụ về cách sử dụng cơ bản CALayer.

CALayer liên quan tới UIView như thế nào?

UIView quản lý rất nhiều thứ bao gồm layout hoặc xử lí các touch event. Điều thú vị là nó không hề quản lý trực tiếp các drawing hay aminations mà CoreAnimation sẽ đảm nhận nhiệm vụ này. Thực tế UIView chỉ bao bọc bên ngoài CALayer. Khi set bound trên một UIView thì view sẽ set bound cho CALayer của nó. Nếu ta gọi layoutIfNeeded trong UIView, lệnh gọi sẽ được truyền tới root CALayer. Mỗi UIView có một root CALayer, mỗi root CALayer có thể chứa nhiều layer con.
Để tìm hiểu về CALayer chúng ta hãy cùng khởi tạo một dự án mới, sau đó tạo một view ở giữa màn hình. Thay thế nội nung của ViewController.swift bằng đoạn code sau:
import UIKit

class ViewController: UIViewController {
  
  @IBOutlet weak var viewForLayer: UIView!
  
  var layer: CALayer {
    return viewForLayer.layer
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    setUpLayer()
  }
  
  func setUpLayer() {
    layer.backgroundColor = UIColor.blue.cgColor
    layer.borderWidth = 100.0
    layer.borderColor = UIColor.red.cgColor
    layer.shadowOpacity = 0.7
    layer.shadowRadius = 10.0
  }

  @IBAction func tapGestureRecognized(_ sender: Any) {
    
  }
  
  @IBAction func pinchGestureRecognized(_ sender: Any) {
    
  }
  
}
Như đã đề cập ở trên, mỗi view trong iOS sẽ liên kết với một layer, chúng ta có thể lấy được layer đó với từ khoá .layer. Đầu tiên, ta tạo một computed property được gọi là layer để truy cập tới layer của viewForLayer. Đồng thời ta cũng gọi setUpLayer() để cài đặt một số thuộc tính cho layer như: đổ bóng, background màu xanh và đường bao lớn màu đỏ. Hãy build project để xem kết quả:

Thật dễ dàng phải không, ta có thể làm việc này với bất cứ view nào trong ứng dụng bởi tất cả các view đều được hỗ trợ bởi layer.

Các thuộc tính cơ bản của CALayer

CALayer có một vài thuộc tính cho phép ta tuỳ chỉnh bề ngoài của nó. Ta đã thay đổi background color của layer từ mặc định không màu sang blue, thêm vào border bằng việc gán border width từ 0 thành 100, đổi màu mặc định từ black sang red và đổ bóng cho nó. Đó là những thuộc tính cơ bản của CALayer, ngoài ra ta còn có thể custom nhiều hơn thế, ví dụ bạn hãy thử thêm đoạn code sau vào:
layer.contents = UIImage(named: "star")?.cgImage
layer.contentsGravity = kCAGravityCenter
Thuộc tính contents của một CALayer cho phép ta set layer content cho một image, trong ví dụ trên ta set cho image star. Hãy thử dùng image nào đó của bạn và chạy app lên, bạn sẽ ngạc nhiên cho xem.

Thay đổi appearance của layer

Hãy thêm tap gesture và pinch gesture recognizers cho view. Sau đó tạo IBAction, và thêm dòng code sau vào:
@IBAction func tapGestureRecognized(_ sender: UITapGestureRecognizer) {
  layer.shadowOpacity = layer.shadowOpacity == 0.7 ? 0.0 : 0.7
}
Khi view nhận tap gesture, viewForLayer sẽ thay đổi shadow opacity của layer giữa 0.7 và 0. Ta có thể override phương thức hitTest() của CALayer để làm điều tương tự. Tuy nhiên layer chỉ có thể gọi hàm hitTest bởi nó không thể nhận được gestures. Vì vậy, ta truyền tap gesture cho view.
Update phương thức pinchGestureRecognized() như sau:
@IBAction func pinchGestureRecognized(_ sender: UIPinchGestureRecognizer) {
  let offset: CGFloat = sender.scale < 1 ? 5.0 : -5.0
  let oldFrame = layer.frame
  let oldOrigin = oldFrame.origin
  let newOrigin = CGPoint(x: oldOrigin.x + offset, y: oldOrigin.y + offset)
  let newSize = CGSize(width: oldFrame.width + (offset * -2.0), height: oldFrame.height + (offset * -2.0))
  let newFrame = CGRect(origin: newOrigin, size: newSize)
  if newFrame.width >= 100.0 && newFrame.width <= 300.0 {
    layer.borderWidth -= offset
    layer.cornerRadius += (offset / 2.0)
    layer.frame = newFrame
  }
}
Ta tạo positive và negative offset dựa trên user pinch, sau đó tuỳ chỉnh kích thước của layer frame, width của border và corner radius của border. Hãy thử chạy project, tap, pinch view và cảm nhận kết quả.
CALayer còn có rất nhiều các thuộc tính và phương thức mà ta có thể linh hoạt sử dụng để tạo ra những UI hay hiệu ứng đẹp. Bạn có thể tìm hiểu sâu hơn về CALayer để áp dụng vào dự án của mình một cách hiệu quả.

Comments

Popular posts from this blog

Alamofire vs URLSession

Alamofire vs URLSession: a comparison for networking in Swift Alamofire and URLSession both help you to make network requests in Swift. The URLSession API is part of the foundation framework, whereas Alamofire needs to be added as an external dependency. Many  developers  doubt  whether it’s needed to include an extra dependency on something basic like networking in Swift. In the end, it’s perfectly doable to implement a networking layer with the great URLSession API’s which are available nowadays. This blog post is here to compare both frameworks and to find out when to add Alamofire as an external dependency. Build better iOS apps faster Looking for a great mobile CI/CD solution that has tons of iOS-specific tools, smooth code signing, and even real device testing? Learn more about Bitrise’s iOS specific solutions! This shows the real power of Alamofire as the framework makes a lot of things easier. What is Alamofire? Where URLSession...

Swift Tool Belt, Part 1: Adding a Border, Corner Radius, and Shadow to a UIView with Interface Builder

During my iOS work, I’ve assembled a set of code that I bring with me on every iOS project. I’m not talking about large frameworks or CocoaPods here. These are smaller Swift extensions or control overrides that are applicable to many projects. I think of them as my tool belt. In this post, I’ll show you an extension that will add a border, a corner radius, and a shadow to any UIView, UIButton, or UILabel and allow you to preview what it will look like in Interface Builder. Back in 2014, I wrote a blog post on Expanding User-Defined Runtime Attributes in Xcode where I added a border, corner radius, and shadow to a UIView using Interface Builder’s user-defined runtime attributes. This solution had no type checking—you had to type the property you wanted to modify by hand and often had to look up what it was called. You also had to run your project in order to see the effect of the runtime attribute. Starting with Xcode 6 , there is a new mech...

Frame vs Bounds in iOS

This article is a repost of an answer I wrote on Stack Overflow . Short description frame = a view’s location and size using the parent view’s coordinate system ( important for placing the view in the parent) bounds = a view’s location and size using its own coordinate system (important for placing the view’s content or subviews within itself) Details To help me remember frame , I think of a picture frame on a wall . The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame’s x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y. To help me remember bound...