2017-08-04 4 views
1

ナビゲーションバーのボタンにカスタム画像を追加しようとしました。しかし、どのような方法を使用しても、画像は常に伸びて見えます。カスタムナビゲーションバーのボタンイメージが引き伸ばされるのはなぜですか?

方法1:

let barbuttonitem = UIBarButtonItem(image: UIImage(named: "apps_small"), style: .plain, target: self, action: nil) 
    navigationItem.leftBarButtonItem = barbuttonitem 

次のように表示されます

Method 1

方法2:

let button = UIButton(type: .custom) 
    button.setImage(UIImage(named: "apps_small"), for: .normal) 
    button.addTarget(self, action: #selector(TeachingRootViewController.appsTouched), for: .touchUpInside) 
    button.frame = CGRect(x: 0, y: 0, width: 10, height: 10) 
    button.bounds = CGRect(x: 0, y: 0, width: 10, height: 10) 
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button) 

それはLが現れますIKEこの:

Method 2

方法3:それはこのようになります

let button = UIButton(type: .custom) 
    button.setImage(UIImage(named: "apps_small"), for: .normal) 
    button.setTitle("Button", for: .normal) 
    button.frame = CGRect(x: 0, y: 0, width: 10, height: 10) 
    button.bounds = CGRect(x: 0, y: 0, width: 10, height: 10) 
    button.imageEdgeInsets = .init(top: 5, left: 5, bottom: 5, right: 300) 
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button) 
    navigationItem.leftBarButtonItem?.imageInsets = .init(top: 5, left: 5, bottom: 5, right: 300) 

Method 3

あなたはタイトルがなくなっている見ることができるように。 UI階層内

、それは次のようになります。

UI Hierarchy

ボタンがナビゲーションバーにあるすべてのスペースを取り上げたことが表示されます。この問題の原因を知っている誰もが

System item

あります:

しかし、システム項目とボタンの問題はありませんか?私はアイデアがなくなったと思う。あなたはこれを

+0

として設定を修正しましたか? –

答えて

0

てみサブビューとして追加する代わりにleftBarButtonItem

var leftButton = UIButton(frame:CGRect(x: 0, y: 0, width: 10, height: 10)) 
var background = UIImageView(image: UIImage(named: "apps_small")) 
background.frame = CGRect(x: 0, y: 0, width: 10, height: 10) 
leftButton.addSubview(background) 
self.navigationController.navigationBar.addSubview(leftButton) 
+0

返信いただきありがとうございます!しかしコンパイルされません... "UINavigationItem型の値に 'addSubview'というメンバーがありません。 UIBarButtonItemには 'addSubview'もありません。 – imxieyi

+0

私はUIBarButtonItemを作成していません。navControllerを使用するためにこれを編集してください。もう一度やり直してください。 –

+0

@imxieyi UIButtonとUINavigationBarをコードとして提供しますか? –

関連する問題