Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift iOS - Tag collection view

Tags:

ios

swift

tags

I'm writing my first iOS app and I wanna just answer what is the best-known solution to make this? It's simple tag collection. I have already looked over the Internet but I have found nothing. I think the best way is to make my own structure of buttons maybe?

Here is what I want to achieve:

Swift Tag collection view

like image 741
Jakub Kontra Avatar asked Mar 20 '15 05:03

Jakub Kontra


2 Answers

enter image description hereI have implemented a tagview using just a collectionview.

Here is the github link.

like image 122
Samiul Islam Sami Avatar answered Oct 23 '22 19:10

Samiul Islam Sami


sometimes you need do it yourself:

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
like image 39
George Avatar answered Oct 23 '22 20:10

George