重构实现:
- 通过扩展实现,低解耦;
- Cell 可自定义,适用范围扩展;
- 下拉列表高度可调整;
- 调用简单;
Screenshot:
UIButton+TopMenu.png
example:
class NNButtonStudyController: UIViewController{
var normlImage = UIImage(named: "icon_selected_no_default")!
var seletedImage = UIImage(named: "icon_selected_yes_green")!
lazy var btn: UIButton = {
let sender = UIButton(type: .custom)
sender.setTitle("默认样式", for: .normal);
// sender.adjustsImageWhenHighlighted = false
if #available(iOS 13.0, *) {
sender.setImage(UIImage.chevron_down, for: .normal)
sender.setImage(UIImage.chevron_up, for: .selected)
}
sender.sizeToFit()
sender.layoutButton(direction: 3, imageTitleSpace: 8)
sender.addTarget(self, action: #selector(handActionBtn(_:)), for: .touchUpInside)
sender.topMenuTarget.items = [String].init(count: 6, generator: { "icon_selected_no_default_\($0)" })
sender.topMenuTarget.selectedBlock = {
let title = sender.topMenuTarget.items[$0]
sender.setTitle(title, for: .normal)
sender.sizeToFit()
sender.layoutButton(direction: 3, imageTitleSpace: 8)
}
sender.topMenuTarget.cellForRowBlock = { tableView, indexPath in
let cell = UITableViewCellOne.dequeueReusableCell(tableView, identifier: UITableViewCellOne.reuseIdentifier, style: .subtitle)
cell.imageView?.image = UIImage.img_update
cell.textLabel?.text = sender.topMenuTarget.items[indexPath.row]
cell.detailTextLabel?.text = sender.topMenuTarget.items[indexPath.row]
return cell
}
return sender
}()
}
// MARK: -life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationItem.titleView = btn
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
btn.topMenuTarget.dismiss(false)
}
//MARK: -functions
@objc func handActionBtn(_ sender: NNButton) {
sender.isSelected.toggle()
if sender.isSelected {
sender.topMenuTarget.show()
} else {
sender.topMenuTarget.dismiss()
}
}
}
Github
网友评论