Swift iOS – 标记集合视图

我正在写我的第一个iOS应用程序,我想回答什么是最好的解决scheme,使这个? 这是简单的标签收集。 我已经浏览了互联网,但是我什么都没有find。 我认为最好的方法是让我自己的button结构也许?

这是我想要达到的:

Swift标签集合视图

只需dynamic地将button添加到superView,并根据您的要求更改背景。

我使用集合视图解决了这个问题。

class FilterController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { @IBOutlet var collectionView: UICollectionView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 150, left: 10, bottom: 150, right: 10) // layout.itemSize = CGSize(width: 90, height: 45) layout.itemSize = CGSizeFromString("Aloha") collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) collectionView!.dataSource = self collectionView!.delegate = self collectionView!.registerClass(TagCell.self, forCellWithReuseIdentifier: "TagCell") collectionView!.backgroundColor = UIColor.whiteColor() self.view.addSubview(collectionView!) } 

有时你需要自己动手:

  let titles = ["Freedom", "God", "Happiness", "Imagination", "Intelligence", "Other"] var buttons = [UIButton]() func createButton(withTitle title: String) -> UIButton { let button = UIButton(type: .System) button.setTitle(title, forState: .Normal) button.titleLabel?.font = UIFont.systemFontOfSize(15.0, weight: UIFontWeightRegular) button.layer.borderWidth = 0.5 button.layer.borderColor = UIColor.lightGrayColor().CGColor button.contentEdgeInsets = UIEdgeInsetsMake(5.0, 15.0, 5.0, 15.0) button.sizeToFit() return button } for title in titles { buttons.append(createButton(withTitle: title)) } func createButtonGrid(withButtons buttons: [UIButton]) { let offset = 5.0 var x = 0.0, y = 0.0, row = 0.0 let viewFrame = CGRectMake(0.0, 0.0, 250.0, 200.0) let view = UIView(frame: viewFrame) view.backgroundColor = UIColor.whiteColor() for idx in 0..<buttons.count { let button = buttons[idx] row += Double(button.frame.width) + offset if row < Double(viewFrame.width) { x = idx == 0 ? offset : row - Double(button.frame.width) } else { x = offset row = Double(button.frame.width) + offset y += Double(button.frame.height) + offset } let frame = CGRectMake(CGFloat(x), CGFloat(y), button.frame.width, button.frame.height) button.frame = frame view.addSubview(button) //quick look } } createButtonGrid(withButtons: buttons)