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

Cách đặt màu nền (background color) cho View trong iOS

UIView là khối xây dựng cơ bản của UI iOS. Thuộc tính backgroundColor xác định màu nền của view.

Cách 1: Storyboard (Interface Builder)

  1. Mở Main.storyboard
  2. Chọn View (hoặc kéo UIView mới)
  3. Attributes Inspector (bên phải) → Background → Chọn màu

Cách đặt màu nền (background color) cho View trong iOS

Cách 2: Code Swift (Programmatically)


override func viewDidLoad() {
    super.viewDidLoad()
    
    // Màu hệ thống (adaptive Dark/Light mode)
    view.backgroundColor = .systemBackground
    view.backgroundColor = .systemRed
    view.backgroundColor = .systemBlue
    
    // Màu custom RGB
    view.backgroundColor = UIColor(red: 0.2, green: 0.6, blue: 0.9, alpha: 1.0)
    
    // Màu Hex (cần extension)
    view.backgroundColor = UIColor(hex: "#3498DB")
    
    // Pattern image
    view.backgroundColor = UIColor(patternImage: UIImage(named: "pattern")!)
}

Cách đặt màu nền (background color) cho View trong iOS

Extension UIColor từ Hex (Tiện ích)


extension UIColor {
    convenience init(hex: String, alpha: CGFloat = 1.0) {
        var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
        hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
        
        var rgb: UInt64 = 0
        Scanner(string: hexSanitized).scanHexInt64(&rgb)
        
        let r = CGFloat((rgb & 0xFF0000) >> 16) / 255
        let g = CGFloat((rgb & 0x00FF00) >> 8) / 255
        let b = CGFloat(rgb & 0x0000FF) / 255
        
        self.init(red: r, green: g, blue: b, alpha: alpha)
    }
}

Semantic Colors (Khuyến nghị iOS 13+)

Tự động thích ứng Light/Dark Mode:

Color Mô tả
.systemBackground Nền chính (trắng light / đen dark)
.secondarySystemBackground Nền thứ cấp (grouped table)
.tertiarySystemBackground Nền cấp 3 (cell trong grouped)
.systemGroupedBackground Nền grouped table (xám nhẹ light / đen dark)
.label Text chính (đен light / trắng dark)
.separator Màu đường kẻ phân cách

Màu động (Dynamic Color) - Dark Mode support


// Tạo màu tự thích ứng
let customColor = UIColor { traitCollection in
    switch traitCollection.userInterfaceStyle {
    case .dark:
        return UIColor(red: 0.1, green: 0.1, blue: 0.2, alpha: 1.0)
    default:
        return UIColor(red: 0.9, green: 0.9, blue: 0.95, alpha: 1.0)
    }
}

view.backgroundColor = customColor

Lưu ý

  • Mặc định backgroundColor = nil → trong suốt
  • Performance: Tránh set backgroundColor trong loop hoặc drawRect
  • Layer: view.layer.backgroundColor dùng CGColor (Core Animation)
  • Safe Area: background color tự mở rộng full screen, không bị safe area che