2017-07-11 106 views
2

有成千上萬的解釋在導航欄中設置圖像,但恕我直言,他們都有同樣的問題:他們使用固定高度的UIImageView,但如果你旋轉設備navigationBar - 高度減小的大小和圖像太高。我試圖用約束來解決這個問題,但我失敗了:如何在navigationBar中正確設置圖片的約束條件?

let imageView = UIImageView(image: UIImage(named: "logo.png")) 
imageView.contentMode = .scaleAspectFit 

self.navigationItem.titleView = imageView 

let height = NSLayoutConstraint(
    item: imageView, attribute: .height, 
    relatedBy: .equal, 
    toItem: self.navigationItem.titleView, attribute: .height, 
    multiplier: 1, constant: 0 
) 
NSLayoutConstraint.activate([ height ]) 

它在橫向模式下不起作用!

回答

0

在這種情況下,您不需要設置約束。導航控制器的標題視圖具有默認約束,以水平和垂直居中,固定寬度和高度。因此,所有你需要做的是設置在您的視圖框的大小做負載

let imageView = UIImageView(image: UIImage(named: "aaa.png")) 
var frame = imageView.frame 
frame.size.height = 30 
frame.size.width = 30 
imageView.frame = frame 
imageView.contentMode = .scaleAspectFit 

self.navigationItem.titleView = imageView 

然後添加一個監聽器來檢測方向變化並相應地改變框的大小。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { 
    let imageView = self.navigationItem.titleView! 
    var frame = imageView.frame 
    if UIDevice.current.orientation.isLandscape { 
     frame.size.height = 10 
     frame.size.width = 10 
    } else { 
     frame.size.height = 30 
     frame.size.width = 30 
    } 
    imageView.frame = frame 
} 

結果看起來是這樣的

enter image description here

相關問題