2015-03-20 3 views
2

Я пишу свое первое приложение для iOS, и я хочу просто ответить на то, что является самым известным решением для этого? Это простая коллекция тегов. Я уже просматривал Интернет, но ничего не нашел. Я думаю, что лучший способ - создать собственную структуру кнопок?Swift iOS - вид коллекции тегов

Вот что я хочу добиться:

Swift Tag collection view

+0

Вы можете использовать кучу кнопок, или вы могли бы сделать это с целью сбора, но не смотреть по всему интернету для решения ; прочитайте документацию и изучите основы, чтобы вы могли делать что-то для себя. – rdelmar

+0

Да, но я думаю, что более полезно, когда я узнаю о лучших практиках и даю здесь ответ с кодом. Спасибо чувак! –

ответ

1

Я решаю эту проблему, используя коллекцию.

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!) 
} 
+0

Его работа для меня, теперь я стилизую его в другом сборнике. Здесь: http://stackoverflow.com/questions/29219739/ios-swift-cgsizefromstring-throws-cgsizezero –

+0

Неправильный путь использования 'CGSizeFromString (« Aloha »)'. Пожалуйста, обратитесь к документации [link] (https://developer.apple.com/reference/uikit/1624484-cgsizefromstring) –

1

Просто динамически добавлять кнопки в SuperView и изменить фон согласно вашему требованию.

2

иногда вам нужно сделать это самостоятельно:

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) 
+0

Swift 3 https://github.com/Brusnikin/Tags-collection-layout –

Смежные вопросы