ios - Swift iOS - 标签 Collection View

标签 ios swift tags

我正在编写我的第一个 iOS 应用程序,我只想回答制作这个应用程序最知名的解决方案是什么?这是简单的标签集合。我已经查看了互联网,但一无所获。我认为最好的方法也许是制作我自己的按钮结构?

这是我想要实现的:

Swift Tag collection view

最佳答案

有时你需要自己做:

import UIKit
import PlaygroundSupport

class TagsView: UIView {

    // MARK: - Properties

    var offset: CGFloat = 5

    // MARK: - Public functions

    func create(cloud tags: [UIButton]) {
        var x = offset
        var y = offset
        for (index, tag) in tags.enumerated() {
            tag.frame = CGRect(x: x, y: y, width: tag.frame.width, height: tag.frame.height)
            x += tag.frame.width + offset

            let nextTag = index <= tags.count - 2 ? tags[index + 1] : tags[index]
            let nextTagWidth = nextTag.frame.width + offset

            if x + nextTagWidth > frame.width {
                x = offset
                y += tag.frame.height + offset
            }

            addSubview(tag)
        }
    }
}

private func button(with title: String) -> UIButton {
    let font = UIFont.preferredFont(forTextStyle: .headline)
    let attributes: [NSAttributedString.Key: Any] = [.font: font]
    let size = title.size(withAttributes: attributes)

    let button = UIButton(type: .custom)
    button.setTitle(title, for: .normal)
    button.titleLabel?.font = font
    button.setTitleColor(.darkGray, for: .normal)
    button.layer.borderWidth = 1.0
    button.layer.cornerRadius = size.height / 2
    button.layer.borderColor = UIColor.darkGray.cgColor
    button.frame = CGRect(x: 0.0, y: 0.0, width: size.width + 10.0, height: size.height + 10.0)
    button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 5.0)
    return button
}

let titles = ["Freedom", "God", "Happiness", "Imagination", "Intelligence", "Other"]
let tags = titles.map { button(with: $0) }

let frame = CGRect(x: 0, y: 0, width: 260, height: 200)
let tagsView = TagsView(frame: frame)
tagsView.backgroundColor = .white
tagsView.create(cloud: tags)

PlaygroundPage.current.liveView = tagsView
PlaygroundPage.current.needsIndefiniteExecution = true

关于ios - Swift iOS - 标签 Collection View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29159938/

相关文章:

json - Swift3:Openweather API 返回 nil 和 API 错误

ios - Swift4.1 : How to remove delivered notification from notification list without open application

javascript - 你如何让标题停留在页面底部,然后在它经过时滚动?

ios - RestKit 对象映射将一个 ID 映射为一个完全不同的负数

iphone - 如何在viewDidAppear方法或viewDidLoad中请求JSON数据?

objective-c - Objective-C - 设置 UIPickerView 委托(delegate)

PHP获取标签之间的字符串[一个字符串中的多个标签]

ios - @IBDesignable - View 未按预期呈现

iOS希望在按下按钮时延迟 View Controller 之间的连接

jquery - javascript、jQuery 和 HTML 标签 : how to check if tags are closed