-1

I want to set image and title both on rightBarButton. Title will come first. I searched a lot but all the articles are related to leftBarButton. So can anyone please tell me, how to set both of them?

func methodForSettingButtonClicked() {
    let buttonSetting = UIButton(type: .custom)
    buttonSetting.frame = CGRect(x: 0, y: 5, width: 25, height: 25)
    let imageReg = UIImage(named: "setting")
    buttonSetting.setTitle("Settings", for: .normal)
    buttonSetting.setImage(imageReg, for: .normal)
    let leftBarButton = UIBarButtonItem()
    leftBarButton.customView = buttonSetting
    self.navigationItem.rightBarButtonItem = leftBarButton;
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579

3 Answers3

0

try barbutton item with custom VIew as follows:-

let button =  UIButton(type: .Custom)
    button.setImage(UIImage(named: "icon_right"), forState: .Normal)
        button.addTarget(self, action: "buttonAction", forControlEvents: .TouchUpInside)
    button.frame = CGRectMake(0, 0, 53, 31)
    button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32)//move image to the right
    let label = UILabel(frame: CGRectMake(3, 5, 50, 20))
    label.font = UIFont(name: "Arial-BoldMT", size: 16)
    label.text = "title"
    label.textAlignment = .Center
    label.textColor = UIColor.whiteColor()
    label.backgroundColor =   UIColor.clearColor()
    button.addSubview(label)
    let barButton = UIBarButtonItem(customView: button)
    self.navigationItem.rightBarButtonItem = barButton

imageEdgeInsets plays a important role.

pkc456
  • 8,350
  • 38
  • 53
  • 109
0

Try it as below and set title as you want

  let button = UIButton(type: .system)
    button.setImage(UIImage(named: "icon_image_name"), for: .normal)
    button.setTitle("Categories", for: .normal)
    button.addTarget(self, action: #selector(clickOnButtonActionMethod), for: .touchUpInside)
    button.sizeToFit()
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)

If you want then change button property as you want.

Govaadiyo
  • 5,644
  • 9
  • 43
  • 72
0

You can do like this way,

    let button = UIButton(type: .custom)
    button.setTitle("Settings", for: .normal)
    button.setImage(#imageLiteral(resourceName: "settings"), for: .normal)
    button.semanticContentAttribute = .forceRightToLeft
    button.setTitleColor(UIColor.white, for: .normal)
    button.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)

It works for me, hope it can help you.

PPL
  • 6,357
  • 1
  • 11
  • 30