简体   繁体   中英

How to add multiple subviews on view without hiding the last added subview?

This is my code

  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]!)

        }

The problem is only the last button added to the view is getting shown. How do I show all the button objects in the view?

EDIT: The frame values for UIButton I am getting

(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
}

This way you have 3 different buttons in buttons . You can also customize the buttons right there as well.

Edit:

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)
}

It looks like button[i]!.frame = CGRectMake(CGFloat(i) *(collectionViewLove?.frame.width)!/3,0,(collectionViewLove?.frame.width)!/3, 30) is producing the same frame each time, so your buttons will be superimposed on each other. You need to have something dynamic in your call to have them be in different spots and visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM