- 1.创建一个button
// MARK: - 懒加载 加号按钮 private lazy var composeBtn: UIButton = { let btn = UIButton() // btn 的加号按钮 btn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: UIControlState.normal) btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted) // btn 的背景图片 btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState.normal) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted) btn.addTarget(self, action: #selector(MainViewController.tap), for: UIControlEvents.touchUpInside) return btn }() // 按钮的点击事件 func tap() { print("kkkkk") }
- 2.在视图想要显示的时候添加
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 添加加号按钮 setcomposeBtn() }
- 3.注意,调用按钮的点击事件不能加private,原因:按钮点击事件的调用是由 运行循环 监听并且以消息机制传递的,因此按钮点击不能设置为private
- 4.加号方法的调用
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 添加加号按钮 setcomposeBtn() } func setcomposeBtn() { // 1.添加加号按钮 tabBar.addSubview(composeBtn) // 2.调整加号按钮的位置 let width = UIScreen.main.bounds.size.width / CGFloat(viewControllers!.count) let rect = CGRect(x: 0,y: 0,width: width,height: 49) // rect:frame dx: x方向的偏移位置 dy: y 方向的偏移位置 composeBtn.frame = rect.offsetBy(dx: 2*width,dy: 0) }
- 重点说一下这个:
rect:frame dx: x
方向的偏移位置dy: y
方向的偏移位置