Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách thêm viền trên và dưới cho View trên iOS

Giới thiệu

Bài viết này hướng dẫn cách vẽ đường viền (border) chỉ ở cạnh trên và cạnh dưới của một UIView bằng cách sử dụng CALayer.

Các bước thực hiện

Bước 1: Tạo dự án

Xcode → New Project → Single View Application → Tên "AddBorderTopAndBottom".

Bước 2: Thêm UIView vào Storyboard

Cách thêm viền trên và dưới cho View trên iOS

Bước 3: Kết nối IBOutlet

Tạo @IBOutlet cho view, đặt tên centerView.

Bước 4: Tạo hàm thêm viền

Viết phương thức tạo hai layer (CALayer) cho viền trên và dưới:

func addTopAndBottomBorders() {
    let thickness: CGFloat = 2.0
    let topBorder = CALayer()
    let bottomBorder = CALayer()
    
    // Viền trên
    topBorder.frame = CGRect(x: 0, y: 0, width: centerView.frame.width, height: thickness)
    topBorder.backgroundColor = UIColor.red.cgColor
    
    // Viền dưới
    bottomBorder.frame = CGRect(x: 0, y: centerView.frame.height - thickness, width: centerView.frame.width, height: thickness)
    bottomBorder.backgroundColor = UIColor.red.cgColor
    
    // Thêm vào layer của view
    centerView.layer.addSublayer(topBorder)
    centerView.layer.addSublayer(bottomBorder)
}

Bước 5: Gọi hàm trong viewDidAppear

Gọi trong viewDidAppear để đảm bảo frame của view đã được layout chính xác:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    addTopAndBottomBorders()
}

Bước 6: Chạy thử

Kết quả hiển thị viền đỏ ở trên và dưới view:

Cách thêm viền trên và dưới cho View trên iOS

Giải thích kỹ thuật

  • CALayer là lớp lõi của Core Animation, nhẹ hơn UIView.
  • frame được tính dựa trên centerView.frame tại thời điểm layout xong.
  • backgroundColor của layer nhận CGColor (không phải UIColor).
  • addSublayer thêm layer con vào cây layer.

Cải tiến: Tạo extension tái sử dụng

extension UIView {
    func addBorders(edges: UIRectEdge, color: UIColor, thickness: CGFloat) {
        if edges.contains(.top) {
            let border = CALayer()
            border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
            border.backgroundColor = color.cgColor
            layer.addSublayer(border)
        }
        if edges.contains(.bottom) {
            let border = CALayer()
            border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
            border.backgroundColor = color.cgColor
            layer.addSublayer(border)
        }
        // Tương tự cho .left, .right
    }
}

// Sử dụng:
centerView.addBorders(edges: [.top, .bottom], color: .red, thickness: 2)

Lưu ý

Nếu view thay đổi kích thước (rotation, auto layout), cần cập nhật lại frame của các border layer trong viewDidLayoutSubviews hoặc sử dụng NSLayoutConstraint với các view con thay vì layer.