我想在Swift 3.0

时间:2017-06-06 05:34:39

标签: ios swift uibutton

我想要的是以编程方式将按钮列表(来自服务的号码)添加到uiview,所以我想我必须检查最后一个按钮和UIView结尾之间的空间是否足以添加按钮或者我必须去下一行?正确?

你能帮帮我吗?

谢谢,

2 个答案:

答案 0 :(得分:1)

你走了。按钮添加了自动布局约束,因此它在所有大小类中的工作方式相同:)

var lastButton : UIButton? = nil

        for i in 0...5 {
            let button = UIButton()
            button.backgroundColor = UIColor.green
            button.setTitle("Button \(i)", for: .normal)
            button.sizeToFit()
            button.translatesAutoresizingMaskIntoConstraints = false

            if i == 0 {
                let viewComponents : [String : Any] = ["button" : button]
                self.view.addSubview(button)
                let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[button]", options: [], metrics: nil, views: viewComponents)
                let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(8)-[button]", options: [], metrics: nil, views: viewComponents)

                self.view.addConstraints(horizontalConstraint)
                self.view.addConstraints(verticalConstraint)
                self.view.layoutIfNeeded()
                lastButton = button
            }
            else {
                if (lastButton != nil) {
                    self.view.addSubview(button)
                    let viewComponents : [String : Any] = ["button" : button, "lastButton" : lastButton!]
                    if (lastButton!.frame.maxX + 8 + button.bounds.size.width) > self.view.bounds.size.width {
                        let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "|-(8)-[button]", options: [], metrics: nil, views: viewComponents)
                        let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:[lastButton]-(8)-[button]", options: [], metrics: nil, views: viewComponents)

                        self.view.addConstraints(horizontalConstraint)
                        self.view.addConstraints(verticalConstraint)
                        self.view.layoutIfNeeded()
                        lastButton = button
                    }
                    else {
                        self.view.addSubview(button)
                        let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "[lastButton]-(8)-[button]", options: [.alignAllTop], metrics: nil, views: viewComponents)

                        self.view.addConstraints(horizontalConstraint)
                        self.view.layoutIfNeeded()
                        lastButton = button
                    }
                }
            }
        }

答案 1 :(得分:-1)

这个想法是使用UICollectionView。您可以使用以下方法实现它:

  1. 使用按钮
  2. 创建自己的单元格UICollectionViewCell
  3. 子类UICollectionViewFlowLayout,覆盖 layoutAttributesForItem(在indexPath:IndexPath),它为每个单元格提供属性。您可能需要在函数prepare()
  4. 中预先计算按钮或单元格的框架
  5. 使用您刚刚子类化的collectionviewLayout创建UICollectionView实例。