Adding a UILabel to a UIToolbar

前端 未结 8 1675
青春惊慌失措
青春惊慌失措 2020-11-27 10:24

I\'m trying to add a label to my toolbar. Button works great, however when I add the label object, it crashes. Any ideas?

UIBarButtonItem *setDateRangeButton         


        
相关标签:
8条回答
  • 2020-11-27 11:10

    Details

    • Xcode 10.2.1 (10E1001), Swift 5

    Full sample

    import UIKit
    
    class ViewController: UIViewController {
    
        private weak var toolBar: UIToolbar?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            var bounds =  UIScreen.main.bounds
            let bottomBarWithHeight = CGFloat(44)
            bounds.origin.y = bounds.height - bottomBarWithHeight
            bounds.size.height = bottomBarWithHeight
            let toolBar = UIToolbar(frame: bounds)
            view.addSubview(toolBar)
    
            var buttons = [UIBarButtonItem]()
            buttons.append(UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ViewController.action)))
            buttons.append(UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(ViewController.action)))
            buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            buttons.append(ToolBarTitleItem(text: "\(NSDate())", font: .systemFont(ofSize: 12), color: .lightGray))
            buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            buttons.append(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action:  #selector(ViewController.action)))
            toolBar.items = buttons
    
            self.toolBar = toolBar
        }
        @objc func action() { print("action") }
    }
    
    class ToolBarTitleItem: UIBarButtonItem {
    
        init(text: String, font: UIFont, color: UIColor) {
            let label =  UILabel(frame: UIScreen.main.bounds)
            label.text = text
            label.sizeToFit()
            label.font = font
            label.textColor = color
            label.textAlignment = .center
            super.init()
            customView = label
        }
        required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
    }
    

    Result

    0 讨论(0)
  • 2020-11-27 11:15

    If you want to adding a view up the toolbar view you can try this:

    [self.navigationController.tabBarController.view addSubview:yourView];
    
    0 讨论(0)
提交回复
热议问题