0

For the life of me, I can't figure out how to center a UIButton in UIScrollView...

let sv = UIScrollView(frame: CGRect(x: 0, y: 0, width: 300, height: 600))
let b = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
sv.addSubview(b)
b.center = sv.center

No matter what I do, the button seems to be off center. This logic works in normal UIView. Why doesn't it with UIScrollView?

7ball
  • 2,183
  • 4
  • 26
  • 61
  • why don't you just put it in the center of UIView? it will always be in the center. – Mina Jun 13 '17 at 04:49
  • The thing is I'd need the button's y position to be after all the content in the scroll view, but still centered in the middle. – 7ball Jun 13 '17 at 05:01

1 Answers1

0

you can also use

let b = UIButton(frame: CGRect(x: sv.frame.size.width/2 -15, y: sv.frame.size.height/2 -15, width: 30, height: 30))

for your code first check value of sv.center, if it is OK and your UI is not updating then call layoutIfneeded

Reference : How is layoutIfNeeded used?

dahiya_boy
  • 9,298
  • 1
  • 30
  • 51