ios - 如何在不隐藏最后添加的 subview 的情况下添加多个 subview ?

标签 ios swift uiview uibutton subview

这是我的代码

  var button = [UIButton?](count:3, repeatedValue: UIButton())
  for i in 0...2{

            button[i]!.tag = i
            button[i]!.frame = CGRectMake(CGFloat(i) *(collectionViewLove?.frame.width)!/3,0,(collectionViewLove?.frame.width)!/3, 30)
            button[i]!.setTitle(titleForButtonsOneSelected[i], forState: .Normal)
            button[i]!.titleLabel?.adjustsFontSizeToFitWidth = true
            button[i]!.layer.borderWidth = 1.0
            button[i]!.layer.borderColor = UIColor.blueColor().CGColor
            button[i]!.backgroundColor = UIColor.clearColor()
            button[i]!.setTitleColor(UIColor.blackColor(), forState: .Normal)
            view.addSubview(button[i]!)

        }

问题是只显示了添加到 View 的最后一个按钮。如何在 View 中显示所有按钮对象?

编辑: 我得到的 UIButton 的帧值

(0.0, 0.0, 106.666666666667, 30.0)

(106.666666666667, 0.0, 106.666666666667, 30.0)

(213.333333333333, 0.0, 106.666666666667, 30.0)

最佳答案

let buttons = Array(0...2).map { number -> UIButton in
    let button = UIButton(frame: CGRectMake(CGFloat(number) * collectionViewLove!.frame.width / 3, 0, collectionViewLove!.frame.width / 3, 30))

    button.tag = number
    button.setTitle(titleForButtonsOneSelected[number], forState: .Normal)
    buttontitleLabel?.adjustsFontSizeToFitWidth = true
    button.layer.borderWidth = 1.0
    button.layer.borderColor = UIColor.blueColor().CGColor
    button.backgroundColor = UIColor.clearColor()
    button.setTitleColor(UIColor.blackColor(), forState: .Normal)
    view.addSubview(button)

    return button
}

这样你在 buttons 中就有了 3 个不同的按钮。您也可以在那里自定义按钮。

编辑:

let buttons = Array(0...2).forEach {
    let button = UIButton(frame: CGRectMake(CGFloat($0) * collectionViewLove!.frame.width / 3, 0, collectionViewLove!.frame.width / 3, 30))

    button.tag = $0
    button.setTitle(titleForButtonsOneSelected[$0], forState: .Normal)
    buttontitleLabel?.adjustsFontSizeToFitWidth = true
    button.layer.borderWidth = 1.0
    button.layer.borderColor = UIColor.blueColor().CGColor
    button.backgroundColor = UIColor.clearColor()
    button.setTitleColor(UIColor.blackColor(), forState: .Normal)
    view.addSubview(button)
}

关于ios - 如何在不隐藏最后添加的 subview 的情况下添加多个 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35667735/

相关文章:

swift : Randomize UIButton Position within View

ios - 从另一个类添加 View 作为 presentViewController 导致 UIEvents 不工作

jquery - 手机上传选择相机

ios - Segue 后向上滚动时 UITableView 滞后

ios - 适用于 iOS 的 Apple 记录的低级用户区 API

ios - 如何在 Swift 中仅打印 2 位数字而不四舍五入?

ios - 如何在 Swift 中删除 UITableView 中的行

ios - 如何使用 Swift 3 覆盖 UIView 中的 requiresConstraintBasedLayout?

ios - Lottie:无法获取带名称的动画

android - 如何为 Android 和 IOS 构建一个库?