스위프트 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)
}
}
이것은 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" 라는 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)