Swift 实现热点标签排列

先上图:


Simulator Screen Shot - iPhone 8 - 2018-02-06 at 16.22.17.png

清空标签之后:


Simulator Screen Shot - iPhone 8 - 2018-02-06 at 16.25.12.png

代码:
BKSearchViewController.swift

class BKSearchViewController: UIViewController {
    
    // 引导搜索
    var guide: BKSearchGuideView!
    // 实时标签
    var mark: BKSearchNewMarkView!

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .groupTableViewBackground

        setupNavigationbar()
        setupSearchNewMarks()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        BKSearchNewMarkViewModel.totalWidth = 0.px
        BKSearchNewMarkViewModel.totalHeight = 0.px
        
    }
}


//MARK: ---------- 导航栏 ----------
extension BKSearchViewController: BKNavigationBarable {
    func setupNavigationbar() {
        guard let navBar = navigationController?.navigationBar else { return }
        let frame = CGRect(x: 0, y: 0,
                           width: BK_SCREEN_WIDTH,
                           height: BK_NAVBAR_HEIGHT(navBar.bounds.height))
        let nav = BKSearchNavigationBar(frame: frame)
        nav.delegate = self
        view.addSubview(nav)
    }
}


//MARK: ---------- 搜索导航引导层 ----------
extension BKSearchViewController {
    fileprivate func setupSearchGuideView() {
        guard let navBar = navigationController?.navigationBar else { return }
        guide = BKSearchGuideView()
        view.addSubview(guide)
        guide.snp.makeConstraints { make in
            make.top.equalTo(view).offset(BK_NAVBAR_HEIGHT(navBar.bounds.height))
            make.left.right.bottom.equalTo(view)
        }
    }
}


//MARK: ---------- 实时标签 ----------
extension BKSearchViewController: BKSearchNewMarkable {
    fileprivate func setupSearchNewMarks() {
        guard let navBar = navigationController?.navigationBar else { return }
        mark = BKSearchNewMarkView()
        mark.delegate = self
        view.addSubview(mark)
        mark.snp.makeConstraints { make in
            make.top.equalTo(view).offset(BK_NAVBAR_HEIGHT(navBar.bounds.height))
            make.left.right.bottom.equalTo(view)
        }
    }
    // 代理 清空标签
    func searchNewMarkClearMarks() {
        let alertController = UIAlertController(title: nil, message: "确定要清空标签吗?", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "确定", style: .default) { [weak self] (action) in
            self?.mark.removeFromSuperview()
            self?.setupSearchGuideView()
        }
        alertController.addAction(okAction)
        alertController.addAction(UIAlertAction(title: "取消", style: .destructive, handler: nil))
        present(alertController, animated: true, completion: nil)
    }
}


//MARK: ---------- 搜索回调代理函数 ----------
extension BKSearchViewController: BKSearchNavigationBarable {
    func searchNavigationBarBack() {
        navigationController?.popViewController(animated: true)
    }
    func searchNavigationBarSearch(content: String) {
        print("正在搜索...")
    }
}

BKSearchViewModel.swift

//MARK: ---------- 搜索的导航栏 ----------
protocol BKSearchNavigationBarable: class {
    /// 返回
    func searchNavigationBarBack()
    /// 搜索
    func searchNavigationBarSearch(content: String)
}
class BKSearchNavigationBar: UIView {
    /// 返回按钮
    var backButton: UIButton!
    /// 搜索框
    var searchTextFiled: UITextField!
    /// 搜索按钮
    var searchButton: UIButton!
    /// 返回和搜索的代理
    var delegate: BKSearchNavigationBarable?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        
        // 返回按钮
        backButton = UIButton(type: .custom)
        backButton.setImage(#imageLiteral(resourceName: "icon_header_back"), for: .normal)
        backButton.setTitleColor(.darkGray, for: .normal)
        backButton.addTarget(self, action: #selector(backButtonPressed), for: .touchUpInside)
        backButton.imageEdgeInsets = BK_BACK_EDGEINSET
        addSubview(backButton)
        
        // 搜索按钮
        searchButton = UIButton(type: .custom)
        searchButton.setTitle("搜索", for: .normal)
        searchButton.setTitleColor(.darkGray, for: .normal)
        searchButton.titleLabel?.font = UIFont.systemFont(ofSize: 13.f)
        searchButton.addTarget(self, action: #selector(searchButtonPressed), for: .touchUpInside)
        addSubview(searchButton)
        
        // 搜索框
        let leftView = UIImageView(image: #imageLiteral(resourceName: "icon_header_search"))
        leftView.contentMode = .scaleAspectFit
        leftView.frame = CGRect(x: 10.px, y: 10.px,
                                width: frame.height-BK_STATUS_HEIGHT-15.px,
                                height: frame.height-BK_STATUS_HEIGHT-20.px)
        
        searchTextFiled = UITextField()
        searchTextFiled.backgroundColor = .groupTableViewBackground
        searchTextFiled.font = UIFont.systemFont(ofSize: 13.f)
        searchTextFiled.textColor = .lightGray
        searchTextFiled.textAlignment = .left
        searchTextFiled.layer.cornerRadius = (frame.height-BK_STATUS_HEIGHT-16.px)/2.px
        searchTextFiled.layer.masksToBounds = true
        searchTextFiled.placeholder = "搜索"
        searchTextFiled.leftView = leftView
        searchTextFiled.leftViewMode = .always
        addSubview(searchTextFiled)
        
        
        backButton.snp.makeConstraints { make in
            make.left.bottom.equalTo(self)
            make.width.height.equalTo(frame.height-BK_STATUS_HEIGHT)
        }
        
        searchButton.snp.makeConstraints { make in
            make.right.bottom.equalTo(self)
            make.width.height.equalTo(frame.height-BK_STATUS_HEIGHT)
        }
        
        searchTextFiled.snp.makeConstraints { make in
            make.left.equalTo(backButton.snp.right)
            make.right.equalTo(searchButton.snp.left).offset(-5.px)
            make.height.equalTo(frame.height-BK_STATUS_HEIGHT-16.px)
            make.bottom.equalTo(self).offset(-8.px)
        }
    }
    
    /// 点击返回按钮 返回到上一页
    @objc private func backButtonPressed() {
        guard let delegate = delegate else { return }
        delegate.searchNavigationBarBack()
    }
    
    /// 点击搜索按钮 开始进行内容搜索
    @objc private func searchButtonPressed() {
        guard let delegate = delegate else { return }
        if let content = searchTextFiled.text {
            if content.count > 0 {
                delegate.searchNavigationBarSearch(content: content)
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


//MARK: ---------- 展示搜索的引导 文章 视频 自媒体 ----------
class BKSearchGuideView: UIView {
    /// 头
    var titleLable: UILabel!
    /// 引导内容层
    var guideView: UIView!
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 头
        titleLable = UILabel()
        titleLable.text = "搜索感兴趣的内容"
        titleLable.textAlignment = .center
        titleLable.font = UIFont.systemFont(ofSize: 17.f)
        titleLable.textColor = .darkGray
        addSubview(titleLable)
        
        // 引导内容层
        guideView = UIView()
        addSubview(guideView)
        
        titleLable.snp.makeConstraints { make in
            make.top.equalTo(self).offset(40.px)
            make.left.right.equalTo(self)
            make.height.equalTo(17.px)
        }
        
        guideView.snp.makeConstraints { make in
            make.top.equalTo(titleLable.snp.bottom).offset(20.px)
            make.left.equalTo(self).offset(60.px)
            make.width.equalTo(BK_SCREEN_WIDTH-120.px)
            make.height.equalTo(80.px)
        }
        
        // 引导内容
        let width = (BK_SCREEN_WIDTH-120.px)/(BKSearchGuideViewModel.guideTitles.count).px
        for (i, v) in BKSearchGuideViewModel.guideTitles.enumerated() {
            let imageView = UIImageView(image: UIImage(named: BKSearchGuideViewModel.guideImages[i]))
            imageView.contentMode = .scaleAspectFit
            guideView.addSubview(imageView)
            
            let label = UILabel()
            label.text = v
            label.textColor = .lightGray
            label.font = UIFont.systemFont(ofSize: 15.f)
            label.textAlignment = .center
            guideView.addSubview(label)
            
            imageView.snp.makeConstraints { make in
                make.left.equalTo(guideView).offset(width*i.px)
                make.top.equalTo(guideView).offset(10.px)
                make.width.equalTo(width)
                make.height.equalTo(width-35.px)
            }
            
            label.snp.makeConstraints { make in
                make.left.equalTo(guideView).offset(width*i.px)
                make.width.equalTo(width)
                make.bottom.equalTo(guideView)
                make.height.equalTo(20.px)
            }
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


//MARK: ---------- 实时标签 ----------
protocol BKSearchNewMarkable: class {
    func searchNewMarkClearMarks()
}
class BKSearchNewMarkView: UIView {
    
    /// 标签底层View
    var markView: UIView!
    /// 清楚标签按钮
    var clearMarkButton: UIButton!
    /// 代理
    var delegate: BKSearchNewMarkable?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 标签底层View
        markView = UIView()
        addSubview(markView)
        
        markView.snp.makeConstraints { make in
            make.top.equalTo(self).offset(20.px)
            make.left.equalTo(self).offset(10.px)
            make.right.equalTo(self).offset(-10.px)
            make.height.equalTo(200.px)
        }
        
        // 绘制实时标签
        var tempTotalWidth: CGFloat = 0.px
        BKSearchNewMarkViewModel.testNewMarks.forEach { value in
            let label = UILabel()
            label.text = value
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: 12.f)
            label.textColor = .lightGray
            label.backgroundColor = .white
            label.layer.cornerRadius = 10.px
            label.layer.masksToBounds = true
            markView.addSubview(label)
            
            let markWidth = BKSearchNewMarkViewModel.getLabelWidth(value.count)+10.px
            tempTotalWidth += markWidth
            if tempTotalWidth > (BK_SCREEN_WIDTH-20.px) {
                tempTotalWidth = markWidth
                BKSearchNewMarkViewModel.totalHeight += 30.px
                BKSearchNewMarkViewModel.totalWidth = 0.px
            }
            
            label.snp.makeConstraints { make in
                make.top.equalTo(markView).offset(BKSearchNewMarkViewModel.totalHeight)
                make.left.equalTo(markView).offset(BKSearchNewMarkViewModel.totalWidth)
                make.width.equalTo(BKSearchNewMarkViewModel.getLabelWidth(value.count))
                make.height.equalTo(20.px)
            }
            
            // 累加每行的总长度
            BKSearchNewMarkViewModel.totalWidth += markWidth
        }
        
        // 更新高度
        markView.snp.updateConstraints { make in
            make.height.equalTo(BKSearchNewMarkViewModel.totalHeight+20.px)
        }
        
        // 清除标签按钮
        clearMarkButton = UIButton(type: .custom)
        clearMarkButton.setTitle("清空标签", for: .normal)
        clearMarkButton.titleLabel?.font = UIFont.systemFont(ofSize: 13.f)
        clearMarkButton.setTitleColor(UIColor(32, 167, 250), for: .normal)
        clearMarkButton.addTarget(self, action: #selector(clearMarkButtonPressed), for: .touchUpInside)
        addSubview(clearMarkButton)
        
        clearMarkButton.snp.makeConstraints { make in
            make.centerX.equalTo(self)
            make.top.equalTo(markView.snp.bottom).offset(10.px)
            make.width.equalTo(100.px)
            make.height.equalTo(45.px)
        }
        
    }
    
    @objc private func clearMarkButtonPressed() {
        guard let delegate = delegate else { return }
        delegate.searchNewMarkClearMarks()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

BKSearchViewModel.swift

//MARK: ---------- 展示搜索的引导 文章 视频 自媒体 ----------
struct BKSearchGuideViewModel {
    /// 引导内容头
    static let guideTitles = ["文章", "视频", "自媒体"]
    /// 引导内容图片
    static let guideImages = ["icon_search_article", "icon_search_video", "icon_search_wemedia"]
}



//MARK: ---------- 实时标签 ----------
struct BKSearchNewMarkViewModel {
    /// 实时标签
    static let testNewMarks = ["还珠格格", "春运", "张学良",
                               "德云社相声", "水哥集锦", "水哥最强大脑",
                               "抖音短视频", "蜘蛛侠", "老梁说天下",
                               "郭德纲", "智行火车票", "58同城",
                               "快牙", "百词斩", "微博",
                               "虾米音乐", "淘宝大学", "千牛",
                               "阿里巴巴", "旺信", "工具",
                               "快手"]
    
    /// 一行的总长度
    static var totalWidth: CGFloat = 0.px
    /// 累加高度
    static var totalHeight: CGFloat = 0.px
    
    static func getLabelWidth(_ count: Int) -> CGFloat {
        switch count {
        case 1:
            return 40.px
        case 2:
            return 50.px
        case 3:
            return 60.px
        case 4:
            return 70.px
        case 5:
            return 80.px
        case 6:
            return 90.px
        default:
            return 100.px
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,016评论 4 62
  • 一 家中太阳能的管子渗水,打电话让维修人员来看看。 当时正值暑假,一开门,一个满脸是汗的小伙子出现在眼前,斜背着一...
    雪域飞燕阅读 507评论 0 1
  • 学会残忍,该杀的就杀【学着无情】一切事情都冷漠以对。一切事情都满不在乎。一切事情都一笑置之。没有心。没有情。 用圆...
    爱唠叨的喵阅读 186评论 0 0
  • 有个单位开民主生活会,领导征求年轻人的意见,本来以为就是走个过场,没人敢说,也不会有人说什么,结果出乎意料,大家一...
    处处1阅读 629评论 0 1
  • 月寄昔时夜,人愿他日春。 此生人未灭,但月惜日坤。
    古月昔阅读 67评论 0 0