简体   繁体   中英

Custom UIToolBar using xib [Swift 3]

Can I create a custom UIToolBar in a Xib file?

I am wanting to make a toolbar with a done button on the far left and a last/next button set on the left side. But I want to make sure that the constraints are such that it will scale correctly for each phone size. Is there an example?

Yes you can. First choose a xib as a template. Name the template "toolbar". 创建XIB

Then delete the default view it gives you. Go to the objects library in the bottom right hand corner and drag out a Toolbar. 拖出工具栏xib

You will get a default Bar Button Item on the far left. Rename this to "Done" then drag out another bar button item and rename it "Next" or "Last". 重命名栏按钮项

Now, create a new file. Choose Cococa Touch Class and make it a subclass of UIToolBar. 在此处输入图片说明

Go back to your tool bar xib and make its class the Cocoa Touch class you just created. In my example, I named mine ToolBarExample.

Now go to your ViewController class. In the ViewDidLoad add the following.

   override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let toolBar = UINib(nibName: "toolbar", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! ToolBarExample

    toolBar.frame = CGRect(x: 0, y: self.view.frame.size.height - 46, width: self.view.frame.size.width, height: 46)

    toolBar.sizeToFit()

    view.addSubview(toolBar)

}

You can change change the scale, size and position of the toolbar by adjusting its frame. You can also adjust the toolbar xib and its bar button items from the Atrributes and Size Inspector. The final product of this example should be as follows in the Simulator.

模拟器中的最终产品

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM