UIButton按鈕自適應(yīng)排布,自動(dòng)換行

1.gif

1.封裝一個(gè)View用來(lái)放所有的button

import UIKit
let SCREEN_WIDTH = UIScreen.main.bounds.size.width
let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
let gap = 10
/// 定義一個(gè)代理方法,在實(shí)現(xiàn)類里面可以獲取到點(diǎn)擊的是哪個(gè)button,這里是傳的index索引,根據(jù)需要可以將參數(shù)變?yōu)閎utton
protocol QYPAdaptiveButtonDelegate:class {
    func searchHistory(index:Int);
}

class QYPAdaptiveButton: UIView {
    weak var delegate:QYPAdaptiveButtonDelegate?
    /// 中間button,記錄選中狀態(tài)
    var tempButton:UIButton?
    /// 按鈕的button中文字?jǐn)?shù)組
    var titleArray = [String]()
    /// 正常時(shí)候顯示的字體大小
    var normal = CGFloat()
    /// 放大時(shí)候顯示的字體大小
    var bigger = CGFloat()
    /// 設(shè)置每一個(gè)按鈕的高度
    var heightBtn = CGFloat()

    class func creat(frame:CGRect,titleArr:[String],normal:CGFloat = 12,bigger:CGFloat = 15,heightBtn:CGFloat = 30) -> QYPAdaptiveButton{
        let v = QYPAdaptiveButton(frame: frame)
        v.titleArray = titleArr
        v.normal = normal
        v.bigger = bigger
        v.heightBtn = heightBtn
        v.setupUI()
        return v
    }
}
extension QYPAdaptiveButton {
    fileprivate func setupUI(){
        // 定義常量 btn的height + 頂部空隙(沒(méi)增加一行的高度)
        let rowHeight:CGFloat = heightBtn + 5
        // 定義一個(gè)變量,用于記錄每一個(gè)btn的x值
        let btnX:CGFloat = CGFloat(gap)
        let btnY:CGFloat = 0
        var x:CGFloat = btnX
        var y:CGFloat = btnY
        // 定義一個(gè)屬性,記錄已經(jīng)是第幾行,然后對(duì)應(yīng)的背景view也要需要增加多高
        var index = 0
        
        // 創(chuàng)建證件類型選擇按鈕
        for i in 0..<titleArray.count {
            let size = titleArray[i].getLabWidth(font: UIFont.systemFont(ofSize: bigger), height: heightBtn)
            if x + size.width > SCREEN_WIDTH {
                index += 1
                x = CGFloat(gap)
                y += rowHeight
            }
            let rect = CGRect(x: x, y: y, width: size.width, height: heightBtn)
            x += size.width + CGFloat(gap)
            let btn = UIButton()
            //2:設(shè)置按鈕的bg圖片與普通圖片

            btn.frame = rect
            btn.setTitle(titleArray[i], for: .normal)
            btn.setTitleColor(UIColor.gray , for: .normal)
            btn.setTitle(titleArray[i], for: .selected)
            btn.setTitleColor(#colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1), for: .selected)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: normal)
            btn.backgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:0.5)
            btn.layer.cornerRadius = 8
            btn.tag = 100 + i
            btn.addTarget(target, action: #selector(chooseOCR), for: .touchUpInside)

            btn.titleLabel?.font = UIFont.systemFont(ofSize: normal)
            if i == 0 {
                btn.titleLabel?.font = UIFont.systemFont(ofSize: bigger)
                btn.isSelected = true
                tempButton = btn
            }
            self.addSubview(btn)
        }
        // 重新設(shè)置self.height的高度
        self.height += CGFloat(index) * rowHeight + rowHeight
    }
    /// 點(diǎn)擊某一個(gè)button的時(shí)候,通過(guò)tag值獲取到了對(duì)應(yīng)的button,然后做出對(duì)應(yīng)的響應(yīng)
    @objc func chooseOCR(btn:UIButton){
        tempButton?.titleLabel?.font = UIFont.systemFont(ofSize: normal)
        tempButton?.isSelected = false
        tempButton = btn
        btn.titleLabel?.font = UIFont.systemFont(ofSize: bigger)
        btn.isSelected = true
        if delegate != nil {
            delegate?.searchHistory(index:btn.tag - 100)
        }
        
    }
}

2.對(duì)了還有一個(gè)東西沒(méi)有加上去,就是寫(xiě)的一個(gè)獲取通過(guò)button里面的文字獲取到文字的長(zhǎng)度來(lái)設(shè)置button的寬度

extension String {
    /// 通過(guò)string動(dòng)態(tài)獲取其對(duì)應(yīng)的size
    /// - font: 字體大小
    func getLabWidth(font:UIFont,height:CGFloat) -> CGSize {
        let size = CGSize(width: 900, height: height)
        let dic = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying)
        let strSize = self.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : Any], context:nil).size
        return strSize
    }
}

上面的這個(gè)extension直接放到上面封裝的view里面就好了,也不要去創(chuàng)建新的文件

3.現(xiàn)在基本上做的封裝已經(jīng)完成,接下來(lái)就是調(diào)用

/// 我這里是測(cè)試下,我在viewController里面寫(xiě)的直接附上所有調(diào)用代碼
import UIKit

class ViewController: UIViewController {

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

        let rect = CGRect(x: 0, y: 100, width: UIScreen.main.bounds.size.width, height: 0)
        let arr = ["把第一個(gè)變長(zhǎng)點(diǎn)","測(cè)試下第二個(gè)","看來(lái)真的要在簡(jiǎn)書(shū)上面寫(xiě)點(diǎn)東西了","測(cè)試2","我先走變長(zhǎng)點(diǎn)試試1","測(cè)試2","測(cè)試1","測(cè)試2","測(cè)試1"]
        let v = QYPAdaptiveButton.creat(frame: rect, titleArr: arr)
        v.delegate = self
        self.view.addSubview(v)
    }
}
/// 遵守協(xié)議,實(shí)現(xiàn)代理方法
extension ViewController:QYPAdaptiveButtonDelegate{
    func searchHistory(index: Int) {
        print(index)
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容