2017-02-11 77 views
0

我看到了this question用於將圖像添加到左側導航欄項目的答案。我成功地做到了。圖像和文本的導航欄按鈕項目。 swift

但我也想添加一個小圖片旁邊的文字。例如,我想顯示用戶有多少個硬幣。所以我需要顯示一個硬幣圖像和它旁邊的硬幣數量。如何做呢?

我試圖設置標題(與「123」),但我只看到圖像,而不是標題。這我的代碼:

let button = UIButton.init(type: .custom) 
    button.setImage(UIImage.init(named: "coins.png"), for: UIControlState.normal) 
    button.addTarget(self, action:#selector(self.callMethod), for: UIControlEvents.touchUpInside) 
    button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) 
    button.setTitle("123", for: UIControlState.normal) 
    let barButton = UIBarButtonItem.init(customView: button) 
    self.navigationItem.leftBarButtonItem = barButton 

謝謝。

回答

0

使用self.navigationItem.leftBarButtonItems這是UIBarButtonItem

let button = UIBarButtonItem() 
let text = UIBarButtonItem() 

self.navigationItem.leftBarButtonItems = [button, text] 
0

數組我覺得你的問題是寬度是30儘量做到更大的像50

let buttonContainer:UIView = UIView() 
buttonContainer.frame = CGRect(x: 0, y: 0, width: 50, height: 32) 

let image = UIImage(named: "coins") 

let button = UIButton.init(type: .system) 
button.setImage(image, for: .normal) 
button.frame = buttonContainer.frame 
button.setTitle("sss", for: .normal)  
button.addTarget(self, action: #selector(action(_:)), for: .touchUpInside) 

buttonContainer.addSubview(button) 
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: buttonContainer) 
2

由於欄按鈕項目與初始化一個自定義視圖,您可以將一個UIImage和一個UILabel添加到一個視圖,以及一個UIButton捕獲觸摸事件,並將其傳遞到初始化程序。

// the UIButton is simply there to capture touch up event on the entire bar button view. 
    let button = UIButton.init(type: .custom) 
    button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) 
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) 
    imageView.image = UIImage(named: "coins") 
    let label = UILabel(frame: CGRect(x: 35, y: 0, width: 50, height: 30)) 
    label.text = "1234" 
    let buttonView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 30)) 
    button.frame = buttonView.frame 
    buttonView.addSubview(button) 
    buttonView.addSubview(imageView) 
    buttonView.addSubview(label) 
    let barButton = UIBarButtonItem.init(customView: buttonView) 
    self.navigationItem.leftBarButtonItem = barButton 

當然,您可能必須根據自己的用途調整幀。