1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- //
- // IHButtonView.swift
- // Inhealth
- //
- // Created by weclouds on 2020/3/17.
- // Copyright © 2020 weclouds. All rights reserved.
- //
- import UIKit
- protocol IHButtonViewDelegate : NSObjectProtocol{
- func numberofItem(in buttonView : IHButtonView)->Int
- func buttonView(_ buttonView: IHButtonView,titleFor item:Int) ->String
- func buttonView(_ buttonView: IHButtonView,didSelected item:Int)
- }
- class IHButtonView: UIView {
- weak var delegate : IHButtonViewDelegate?
- var buttonArr :[UIButton]? = [UIButton]()
-
- override init(frame: CGRect) {
- super.init(frame: frame)
- }
-
- required init?(coder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
-
- func reloadData() {
- self.removeSubviews()
- createButtons()
- }
- //创建按钮
- func createButtons() {
- let bgViewWidth :CGFloat = KSCREENWIDTH - 40 - 20
- let space :CGFloat = 17
- var buttonX :CGFloat = 10
- var buttonY : CGFloat = 10
- // let buttonW :CGFloat = (bgViewWidth - 3 * space) / 4
- let buttonH :CGFloat = 30
- let count = delegate?.numberofItem(in: self )
- for i in 0..<count! {
- let title = delegate?.buttonView(self, titleFor: i)
- // let col : Int = i % 4 //列
- // let row : Int = i / 4 // 行
- let str_width = title!.ga_widthForComment(font: UIFont(name: PingFangSC_Regular, size: 13)!, height: 30)
- let btnW = str_width + 20
-
- if buttonX + btnW > bgViewWidth{
- buttonX = 20
- buttonY += 40
- }
- let btn = UIButton(type: .custom)
- btn.frame = CGRect(x: buttonX, y: buttonY, width: btnW, height: buttonH)
- btn.setTitle(title, for: .normal)
- btn.backgroundColor = UIColor(hexString: "#FFFFFF")
- btn.setTitleColor(UIColor(hexString: "#333333"), for: .normal)
- btn.setTitleColor(UIColor(hexString: "#FFFFFF"), for: .selected)
- btn.titleLabel?.font = UIFont(name: PingFangSC_Regular, size: 13)
- btn.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
-
- btn.tag = 1023243 + i
- btn.layer.masksToBounds = true
- btn.layer.cornerRadius = 4
- if i == 0 {
- btn.isSelected = true
- btn.backgroundColor = UIColor(hexString: "#573F95")
- }
- self.addSubview(btn)
- self.buttonArr?.append(btn)
- buttonX += (btnW + 10)
- }
- }
- @objc func buttonClick(_ sender:UIButton) {
- for btn in buttonArr! {
- btn.isSelected = false
- btn.backgroundColor = UIColor(hexString: "#FFFFFF")
- }
- sender.isSelected = true
- sender.backgroundColor = UIColor(hexString: "#573F95")
- if let delegate = self.delegate {
- delegate.buttonView(self, didSelected: sender.tag - 1023243)
- }
- }
-
- override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
- super.touchesBegan(touches, with: event)
- log.debug("点击了 - buttonView")
- }
- }
|