การสร้างประสบการณ์แบบองค์รวมและบูรณาการจำเป็นต้องมีธีม การเปลี่ยนสีของมุมมองทั้งหมดเพื่อรองรับธีมนั้นเป็นกระบวนการที่วุ่นวาย เพื่อหลีกเลี่ยงไม่ให้โค้ดซ้ำซ้อน เราใช้คุณสมบัติtintColor ใน SwiftUI สีอ่อนนี้จะถูกเปลี่ยนชื่อเป็น AccentColor ในบทช่วยสอนนี้ เราจะเรียนรู้ทั้งสองอย่าง
โทนสี UIKit
- ใน UIKit TintColor จะสะท้อนไปยังส่วนควบคุมทั้งหมด (เช่น: Button Slider ฯลฯ ) พร้อมกับ Templet Image
- สีอ่อนที่ตั้งค่าเป็นพาเรนต์จะเผยแพร่ไปยัง ลูกทั้งหมด หากมุมมองลูกต้องการแทนที่สีอ่อน มันสามารถกำหนดโทนสีที่แตกต่างกันได้
class ViewController: UIViewController { @IBOutlet weak var image: UIImageView! //UIImageView have templet image @IBOutlet weak var button2: UIButton! @IBOutlet weak var button1: UIButton! override func viewDidLoad() { super.viewDidLoad() button1.tintColor = .green self.view.tintColor = .red // parent tint } }
- Global Tintสามารถตั้งค่าเพื่อให้ส่วนควบคุมทั้งหมด (ปุ่ม แถบเลื่อน รูปภาพ Templet ฯลฯ) มีสีเดียวกันในทุกหน้าจอ
การใช้โค้ด ตั้งค่าโทนสีเป็นหน้าต่าง:
class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } window = UIWindow(frame: windowScene.coordinateSpace.bounds) window?.windowScene = windowScene window?.tintColor = UIColor.green //set global tint } }
สำเนียงสี SwiftUI
พฤติกรรมของ AccentColor นั้นเหมือนกับ SwiftUI ทุกประการ แต่ใช้ไม่ได้กับรูปภาพ
import SwiftUI struct ContentView: View { @State private var showSwitch = true @State private var temp: Double = 0 var body: some View { VStack(spacing: 10){ Button("Button") { }.padding() Image.init("star").padding() Image.init(systemName: "heart").foregroundColor(.blue).colorMultiply(.red).padding() //accentColor does not affect Image Slider(value: $temp, in: -100...100, step: 1) //Works //overrride parent accentColor Button("Button2") { }.accentColor(.blue).padding() }.accentColor(.red) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
การตั้งค่าธีมสากล:
เปลี่ยนมุมมองแรกดังต่อไปนี้เพื่อให้สะท้อนให้เห็นในแอปทั้งหมด:
class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow ? //set theme here let contentView = ContentView().accentColor(.red) // Use a UIHostingController as window root view controller. if let windowScene = scene as ? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } }
- หมายเหตุเนื่องจากการดูไม่เคยไปกับ ContentView_Previews สีบนผ้าใบจะไม่สะท้อน หากต้องการให้สีสะท้อนบน Canavas ให้อัปเดต AccentColor ของ ContentView_Previews