Добавление UIButton на панель инструментов Swift 5 - PullRequest
1 голос
/ 01 ноября 2019

, поэтому я прочитал другие периоды переполнения стека, и ни один из них мне не помогУ меня есть кусок кода, который создает мой UIButton, который находится здесь:

let haveAccountButton: UIButton = {
    let HColor = UIColor(red: 89/255, green: 156/255, blue: 120/255, alpha: 1)
    let HFont = UIFont.systemFont(ofSize: 16)
    let HSColor = UIColor(red: 239/255, green: 47/255, blue: 102/255, alpha: 1)

    let HButton = UIButton(type: .system)
    let attributedTitle = NSMutableAttributedString(string:
        NSLocalizedString("Already have an account?", comment: ""), attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray, NSAttributedString.Key.font: HFont])
    attributedTitle.append(NSAttributedString(string: NSLocalizedString(" Sign In", comment: ""), attributes: [NSAttributedString.Key.foregroundColor: HSColor, NSAttributedString.Key.font: HFont]))
    HButton.addTarget(self, action: #selector(signinAction), for: .touchUpInside)

    HButton.setAttributedTitle(attributedTitle, for: .normal)

    return HButton
}()

Я уже установил navigationController? .IsToolbarHidden = false в viewDidLoad. у меня вопрос: как сделать так, чтобы кнопка отображалась на панели инструментов?

ОБНОВЛЕНИЕ: в настоящее время этот код будет работать без панели инструментов следующим образом:

import Foundation
import UIKit

class SignUpControllerSave: UIViewController {


let haveAccountButton: UIButton = {
    let HColor = UIColor(red: 89/255, green: 156/255, blue: 120/255, alpha: 1)
    let HFont = UIFont.systemFont(ofSize: 16)
    let HSColor = UIColor(red: 239/255, green: 47/255, blue: 102/255, alpha: 1)

    let HButton = UIButton(type: .system)
    let attributedTitle = NSMutableAttributedString(string:
        NSLocalizedString("Already have an account?", comment: ""), attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray, NSAttributedString.Key.font: HFont])
    attributedTitle.append(NSAttributedString(string: NSLocalizedString(" Sign In", comment: ""), attributes: [NSAttributedString.Key.foregroundColor: HSColor, NSAttributedString.Key.font: HFont]))
    HButton.addTarget(self, action: #selector(signinAction), for: .touchUpInside)

    HButton.setAttributedTitle(attributedTitle, for: .normal)

    return HButton
}()

//potential gradient background if wanted
func setGradientBackground() {
    let top_Color = UIColor(red: 203/255, green: 215/255, blue: 242/255, alpha: 1.0).cgColor
    let bottom_Color = UIColor(red: 181/255, green: 199/255, blue: 242/255, alpha: 1.0).cgColor
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [top_Color, bottom_Color]
    gradientLayer.locations = [0, 1]
    gradientLayer.frame = self.view.bounds
    self.view.layer.insertSublayer(gradientLayer, at: 0)
}

override func viewDidLoad() {
    super.viewDidLoad()
    //view.backgroundColor = .yellow
    navigationController?.isNavigationBarHidden = true
    navigationController?.isToolbarHidden = false
    navigationItem.title = NSLocalizedString("Membership", comment: "")
    setupHaveAccountButton()
}

override func viewWillAppear(_ animated: Bool) {
    navigationController?.isNavigationBarHidden = true
    navigationController?.isToolbarHidden = false
    setGradientBackground()
    super.viewWillAppear(animated)
}

@objc func signinAction() {
    navigationController?.popViewController(animated: true)
}

fileprivate func setupHaveAccountButton() {
    view.addSubview(haveAccountButton)
    haveAccountButton.anchors(top: nil, topPad: 0, bottom: view.safeAreaLayoutGuide.bottomAnchor,
                              bottomPad: 8, left: view.leftAnchor, leftPad: 0, right: view.rightAnchor,
                              rightPad: 0, height: 20, width: 0)
}

}

ОБНОВЛЕНИЕ: предыдущий ответ позволил кнопке теперь находиться на панели инструментов, но целевое действие кнопки не работает. Я попытался добавить .sizeToFit (), где я могу, и посмотрел на многих веб-сайтах все безрезультатно. Кто-нибудь знает, как мне решить проблему с кнопкой?

1 Ответ

1 голос
/ 01 ноября 2019

Этот код должен работать так, как вы хотите:

class SignUpControllerSave: UIViewController {

    /* the other code you posted can be used without changes */

    fileprivate func setupHaveAccountButton() {
        toolbarItems = [
            UIBarButtonItem(customView: haveAccountButton)
        ]
    }

}

Поскольку это может вызвать проблемы с обработчиком кликов, попробуйте это (что выглядит почти так же - за исключением размера шрифта):

class SignUpControllerSave: UIViewController {


    fileprivate func setupHaveAccountButton() {
        let haveAccountLabel = UILabel()
        haveAccountLabel.font = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
        haveAccountLabel.text = NSLocalizedString("Already have an account?", comment: "")
        haveAccountLabel.textColor = .lightGray

        toolbarItems = [
            UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
            UIBarButtonItem(customView: haveAccountLabel),
            UIBarButtonItem(title: "Sign In", style: .plain, target: self, action: #selector(self.signinAction)),
            UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        ]
        navigationController?.toolbar.tintColor = UIColor(red: 239/255, green: 47/255, blue: 102/255, alpha: 1)
    }

}
...