2016-04-15 191 views
2

我一直在如何在左側對齊的NavigationBar中獲取圖像。我明白如何替換中間的標題。在左側對齊的導航欄中添加一個徽標

基本上,我有一個視圖控制器嵌入導航欄控制器。在該視圖控制器中,我在中間有一個搜索表單,右側有一個酒吧按鈕,我正在嘗試將徽標放在左側的圖像中。

下面是我理解如何放置圖像,但我如何讓它左對齊?

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) 
imageView.contentMode = .ScaleAspectFit 
let image = UIImage(named: "imageName") 
imageView.image = image 
navigationItem.titleView = imageView 

回答

8

您可以指定項目的數組到navigationBarleftBarButtonItems財產。您應該添加一個數組,因爲左側和徽標之間通常沒有空格,這看起來不太好。這裏是一個例子:

func setUpUI() { 
    let logoImage = UIImage.init(named: "logoImage") 
    let logoImageView = UIImageView.init(image: logoImage) 
    logoImageView.frame = CGRectMake(-40, 0, 150, 25) 
    logoImageView.contentMode = .ScaleAspectFit 
    let imageItem = UIBarButtonItem.init(customView: logoImageView) 
    let negativeSpacer = UIBarButtonItem.init(barButtonSystemItem: .FixedSpace, target: nil, action: nil) 
    negativeSpacer.width = -25 
    navigationItem.leftBarButtonItems = [negativeSpacer, imageItem] 
} 

它的左側的負間隔將推它一下,你可以從那裏調整它。

+0

這太棒了。完美工作。負面墊片是一個好主意。謝謝! – kelsheikh

0

用Image創建一個BarButton項目。

將其作爲左欄按鈕項目分配給導航欄,如下所示。

目標C

UIBarButtonItem *logo = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:"imageName"] style:UIBarButtonItemStylePlain target:self action:@selector(methodName)]; 

self.navigationItem.leftBarButtonItem = logo; 

SWIFT

let logo = UIBarButtonItem(image: UIImage (named: "imageName"), style: UIBarButtonItemStyle.plain, target: self, action: methodName) 

self.navigationItem.leftBarButtonItem = logo 

希望它可以幫助..

+0

在Objective-C的例子,不應樣式進行UIBarButtonItemStylePlain ...? –

+0

是@JoshB更新了上面的答案。 –

2

對於iOS 11,我們需要添加約束的BarButtomItem

func addLeftBarIcon(named:String) { 

    let logoImage = UIImage.init(named: named) 
    let logoImageView = UIImageView.init(image: logoImage) 
    logoImageView.frame = CGRect(x:0.0,y:0.0, width:60,height:25.0) 
    logoImageView.contentMode = .scaleAspectFit 
    let imageItem = UIBarButtonItem.init(customView: logoImageView) 
    let widthConstraint = logoImageView.widthAnchor.constraint(equalToConstant: 60) 
    let heightConstraint = logoImageView.heightAnchor.constraint(equalToConstant: 25) 
    heightConstraint.isActive = true 
    widthConstraint.isActive = true 
    navigationItem.leftBarButtonItem = imageItem 
} 

圖像視圖中的所有最佳

相關問題