斯威夫特 5.2 Xcode 11.4
Apple Symbol chevron.left现在允许更优雅的解决方案来制作自定义按钮。我已经尽可能地匹配大小和间距。
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)
}
}
这可以实现为 aUIToolbarItem
或 aUINavigationItem
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”的Apple 符号
将以下代码添加到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)