[swift] Swift Core Graphics로 그리드 형태의 뷰 구성하기

Swift에서 Core Graphics를 사용하여 그리드 모양의 뷰를 생성하는 방법에 대해 설명하겠습니다.

1. Core Graphics를 이용한 뷰 생성

import UIKit

class GridView: UIView {
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        let context = UIGraphicsGetCurrentContext()
        context?.setStrokeColor(UIColor.black.cgColor)
        context?.setLineWidth(1.0)
        
        let rows = 8
        let columns = 8
        
        let cellWidth = bounds.size.width / CGFloat(columns)
        let cellHeight = bounds.size.height / CGFloat(rows)
        
        for i in 0...rows {
            context?.move(to: CGPoint(x: 0, y: CGFloat(i) * cellHeight))
            context?.addLine(to: CGPoint(x: bounds.size.width, y: CGFloat(i) * cellHeight))
        }
        
        for i in 0...columns {
            context?.move(to: CGPoint(x: CGFloat(i) * cellWidth, y: 0))
            context?.addLine(to: CGPoint(x: CGFloat(i) * cellWidth, y: bounds.size.height))
        }
        
        context?.strokePath()
    }
}

// 뷰에 그리드 추가
let gridView = GridView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))

위의 코드는 Swift에서 GridView 클래스를 생성하고, draw 메서드에서 Core Graphics를 사용하여 그리드를 그리는 방법을 보여줍니다.

2. 그리드 뷰의 사용

그리드 뷰의 인스턴스를 만든 후에는 다른 뷰와 마찬가지로 사용할 수 있습니다.

// 뷰 컨트롤러에 그리드 추가
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let gridView = GridView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        view.addSubview(gridView)
    }
}

이제 그리드 모양의 뷰를 Core Graphics를 사용하여 만드는 방법을 알았습니다. Core Graphics는 매우 다양한 도형과 효과를 그리는 데 사용할 수 있으며, 이를 응용하면 다양한 사용자 정의 뷰를 만들 수 있습니다.

더 많은 정보를 원하시면 Apple 공식 문서의 Core Graphics Guide를 참고하시기 바랍니다.

이상으로 Swift Core Graphics를 사용하여 그리드 모양의 뷰를 만드는 방법에 대해 알아보았습니다.