Captain Dilan
Captain Dilan

Reputation: 81

move a nav bar button a little to the right

I enter image description herehave this login page and I want to be able to modify the back button. I want to move the back button to the right, I tried the CGRect command but it didnt work. How can I move this arrow to the right. Thank you.

var layoutGuide:UILayoutGuide!
func addBackButton() {


    if #available(iOS 11.0, *) {
        layoutGuide = view.safeAreaLayoutGuide
    } else {
        // Fallback on earlier versions
        layoutGuide = view.layoutMarginsGuide
    }
    let backButton = UIButton(type: .custom)
    backButton.setImage(UIImage(named: "arrow.png"), for: .normal) // Image can be downloaded from here below link
    backButton.setTitleColor(backButton.tintColor, for: .normal) // You can change the TitleColor
    backButton.tintColor = blueColors
    backButton.frame = CGRect(x: 40, y: 0, width: 30, height: 30)
    backButton.translatesAutoresizingMaskIntoConstraints = false
    backButton.addTarget(self, action: #selector(self.backAction(_:)), for: .touchUpInside)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)


}
@objc func backAction(_ sender:UIButton) -> Void {
    self.navigationController?.popViewController(animated: true)
}

Upvotes: 0

Views: 1618

Answers (3)

Fabio
Fabio

Reputation: 5638

Try to set your button like this:

func addBackButton() {
    let backButton = UIButton(type: .custom)
    backButton.setImage(UIImage(named: "arrow.png"), for: .normal)
    backButton.setTitleColor(.blue, for: .normal)
    backButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    backButton.addTarget(self, action: #selector(self.backAction(_:)), for: .touchUpInside)

    let view = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 30))
    view.bounds = view.bounds.offsetBy(dx: -40, dy: 0)
    view.addSubview(backButton)
    let backButtonView = UIBarButtonItem(customView: view)

    navigationItem.leftBarButtonItem = backButtonView
}

Hope this help :)

Upvotes: 2

nicksarno
nicksarno

Reputation: 4245

If you want the button on the right side, just change self.navigationItem.leftBarButtonItem to self.navigationItem.rightBarButtonItem.

Otherwise, since you have nothing else in the Navigation bar, just get rid of the Navigation bar entirely and add a normal button where you want the back button to be.

Upvotes: 0

grow4gaurav
grow4gaurav

Reputation: 3305

To keep this button in the center:

self.navigationItem.titleView = backButton;

To keep this button in the right:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: backButton)

Upvotes: 0

Related Questions