Swift 5.2 Xcode 11.4
苹果标志雪佛龙。左边现在允许一个更优雅的解决方案,使一个自定义按钮。我已经尽可能地匹配了大小和间距。
import UIKit
class CustomBackButton: UIBarButtonItem {
convenience init(target: Any, selector: Selector) {
// Create UIButton
let button = UIButton(frame: .zero)
// Customise Title
button.setTitle("Back", for: .normal)
button.setTitleColor(.systemBlue, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 17)
// Customise Image
let config = UIImage.SymbolConfiguration(pointSize: 19.0, weight: .semibold, scale: .large)
let image = UIImage(systemName: "chevron.left", withConfiguration: config)
button.setImage(image, for: .normal)
// Add Target
button.addTarget(target, action: selector, for: .touchUpInside)
// Customise Spacing to match system Back button
button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: -18.0, bottom: 0.0, right: 0.0)
button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -12.0, bottom: 0.0, right: 0.0)
self.init(customView: button)
}
}
这可以实现为一个UIToolbarItem,或UINavigationItem
override func viewDidLoad() {
super.viewDidLoad()
// UIToolbar Item
let barBackButton = CustomBackButton(target: self, selector: #selector(backButtonTapped))
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
navigationController?.setToolbarHidden(false, animated: false)
toolbarItems = [barBackButton, flexSpace]
// Navigation Item
let navBackButton = CustomBackButton(target: self, selector: #selector(backButtonTapped))
navigationItem.leftBarButtonItem = navBackButton
}
@objc func backButtonTapped() {
print("Back tapped")
}
如果你想翻转按钮,让箭头指向右侧:
使用命名为“chevron.right”的苹果符号
将以下代码添加到CustomBackButton类:
// Put the image of the right side of the button
button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)