swift - 以编程方式创建动态多个 UIButton

标签 swift uibutton swift4

我正在以编程方式创建我的 UI,这就是我创建按钮的方式

let button: UIButton = {

let button = UIButton()
button.setTitle("Try1",.normal)
return button

}

enter image description here

这就是我想做的。例如 movie1 有 2 个类别,Dram & Horror 我只想展示其中的 2 个。 Movie2 有 4 个类别,Dram&Horror&Sport&War 我只想展示其中的 4 个。

现在我卡住了,不知道该怎么办。我知道你们会给出负面评价,但我需要帮助。

完成!解决方案如下

首先我做了一个结构体

struct Category {
let title: String
let color: UIColor
init(title: String, color: UIColor) {
    self.title = title
    self.color = color
}
}

然后我做了一个Category Struct的空数组类型

var categories = [Category]()
/* I appended some stuff manually to this array */
    categories.append(Category(title: "Dram", color: Colors.cherry))
    categories.append(Category(title: "Sport", color: Colors.lightGreen))
    categories.append(Category(title: "Horror", color: Colors.purple))
    categories.append(Category(title: "War", color: Colors.darkBlue))

/* Then I made a for loop */
 for category in categories{
        let button = UIButton()
        button.createButton(title: category.title, titleColor: .white, fontType: "bold", fontSize: 17, background: category.color, cornerRadius: 4)
        stackView.addArrangedSubview(button)
    }

enter image description here

最佳答案

为此使用 Horizo​​ntal StackView。在 StackView 中,您可以根据需要添加尽可能多的排列 subview ,它会自动调整到可用空间。只需为 StackView 设置约束,其余的就可以开箱即用。

您可以使用以下方法将按钮添加到 StackView:

stackView.addArangedSubview(button)

要创建按钮,您可以简单地使用 for 循环:

for i in 1...3 { //change 3 to your value
    let button = UIButton()
    stackView.addArangedSubview(button)
}

关于swift - 以编程方式创建动态多个 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45612514/

相关文章:

ios - gRPC-Core Apple Mach-O 链接器错误

ios - 当我使用 SKPhysicsBody(纹理 :size:) to create physics body I got an issue

ios - SpriteKit - 对在多个 SKNode 上运行的多个 SKAction 进行排序

ios - 在 iPad 中显示矢量 map

ios - 如何检查更新是否可用 - Swift 4.2 iOS 12

ios - 如何获取属性字符串的字符串范围?

ios - 无法在 Objective C 类中使用 Swift 协议(protocol),因为它会导致段错误 : 11

ios - 如何通过单击 tableview 单元格上的按钮来获取文档 ID?

ios - 关于@selector 和 MVC

ios - 循环,使用数组中的函数生成按钮