SWIFT 2.X:
進出方便,我已經擴展UIImage()
,讓我基本上是把它當作立即用下面的代碼的顏色。
extension UIImage {
class func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRectMake(0, 0, 1.0, 0.5)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
接下來,你需要下面的行添加到您的代碼調整的viewController的UINavigationBar
的陰影圖像,或顏色在這種情況下。
// Sets Bar's Background Image (Color) //
self.navigationController?.navigationBar.setBackgroundImage(UIImage.imageWithColor(UIColor.blueColor()), forBarMetrics: .Default)
// Sets Bar's Shadow Image (Color) //
self.navigationController?.navigationBar.shadowImage = UIImage.imageWithColor(UIColor.redColor())
SWIFT 3.X/4.x的:
擴展代碼:
extension UIImage {
class func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 0.5)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
導航欄代碼:
// Sets Bar's Background Image (Color) //
navigationController?.navigationBar.setBackgroundImage(UIImage.imageWithColor(color: .blue), for: .default)
// Sets Bar's Shadow Image (Color) //
navigationController?.navigationBar.shadowImage = UIImage.imageWithColor(color: .red)
編輯1:
更新擴展代碼,這樣就可以在不改變UIImage
顏色不透明度調整矩形的大小。
編輯2:
新增夫特3 + 4斯威夫特代碼。
陰影圖像仍然存在,你必須做'UINavigationBar.appearance()。shadowImage = ...'在Swift – dan
有誰知道爲什麼自動完成不顯示shadowImage? (但它確實存在,實際上) – TIMEX
因爲它不能通過'UINavigationBar.appearance()'訪問。 – ZGski