//懒加载工具条 private lazy var toolBar: UIToolbar = UIToolbar() //设置底部的工具条 private func setToolBar() { //添加子控件 view.addSubview(toolBar) //添加约束 toolBar.snp_makeConstraints { (make) -> Void in make.bottom.left.right.equalTo(view) make.height.equalTo(40) } //通过数组设置toolBar var items = [UIBarButtonItem]() //添加 UIBarButtonItem let itemSettings = [["imageName" : "compose_toolbar_picture"],["imageName" : "compose_mentionbutton_background"], ["imageName" : "compose_trendbutton_background"], ["imageName" : "compose_emoticonbutton_background"], ["imageName" : "compose_add_background"]] //遍历itemSettings for dict in itemSettings { let btn = UIButton(type: .Custom) let imageName = dict["imageName"]! //设置图片 btn.setImage(UIImage(named: imageName), forState: .Normal) btn.setImage(UIImage(named: imageName + "_highlighted"), forState: .Highlighted) let item = UIBarButtonItem(customView: btn) btn.sizeToFit() //把item添加到数组中 items.append(item) //实例化弹簧 let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) items.append(space) } //删除最后一个弹簧 items.removeLast() //添加到toolBar上 toolBar.items = items }
执行结果: