2016-05-16 93 views
7

我讀了很多主題,但沒有一個能夠以最清晰,一致的答案解答這個問題,以解決最新版本的Swift問題。例如,this question的最佳答案建議UINavigationBar.appearance().setShadowImage()。但是,這種方法在最新版本的swift中不存在。如何更改UINavigationBar底部邊框的顏色?

不想隱藏的底部邊框。我只想更改顏色

此外,能夠改變高度會很棒,但我知道我在一個問題中要求太高。

編輯:我創建了一個2×1像素的圖像,並將其設置爲的ShadowImage,但邊界保持不變:

UINavigationBar.appearance().barTintColor = UIColor.whiteColor() 
UINavigationBar.appearance().shadowImage = UIImage(named: "border.jpg") //in my AppDelegate, for global appearance 

這裏的圖像;它真的很小:border image

+2

陰影圖像仍然存在,你必須做'UINavigationBar.appearance()。shadowImage = ...'在Swift – dan

+0

有誰知道爲什麼自動完成不顯示shadowImage? (但它確實存在,實際上) – TIMEX

+0

因爲它不能通過'UINavigationBar.appearance()'訪問。 – ZGski

回答

0

像UI這樣舊的UIKit設置方法已經重新配置,以便您可以直接使用=標誌設置它們。所以,在我的例子中,你將不得不使用UISomeClass.something = whatIWantToSet。你的情況是UINavigationBar.appearance().shadowImage = whatYouWantToSet

13

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斯威夫特代碼。

+0

你知道嗎,爲什麼我改變你的矩形的高度/寬度到''0.5''',顏色會改變? – TIMEX

+0

@TIMEX,我更新了我的代碼,所以這不應該發生了 – ZGski