Gaurav Saini
Gaurav Saini

Reputation: 177

How to add custom View according to UIButton location in swift?

I am trying to add custom View on button action. custom View is add successfully, but it's not show properly

@IBAction func sideButtonAction(_ sender: UIButton) {
    sideSubView = SideView(frame: CGRect(x: sender.frame.origin.x ,y: sender.frame.origin.y + 40,width: 200,height: 200))
    self.view.addSubview(sideSubView)
}

In UIView class

func xibSetup() {
    view = loadViewFromNib()
    view.frame = bounds
    view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
    addSubview(view)
}

override init(frame: CGRect) {
    super.init(frame: frame)
    xibSetup()
}

enter image description here

In screenshot, blue View is custom view, it's not show properly, I have set height and width is 200.

Thanks

Upvotes: 1

Views: 781

Answers (3)

DJ_Mobi90
DJ_Mobi90

Reputation: 139

Its look like your button on Navigationbar and you are adding blue view on controller's view. Both view are different so point coordinate will be different for both. You need to pass relative coordinate to your blue view's frame.

Upvotes: 0

Malik
Malik

Reputation: 3802

The screenshot shows the code working as it should. Your view starts underneath the button and moves right. I'm assuming that you wanted the whole 200 width and height visible under the button. If that is the case, then you need to change this line

sideSubView = SideView(frame: CGRect(x: sender.frame.origin.x ,y: sender.frame.origin.y + 40,width: 200,height: 200))

to

sideSubView = SideView(frame: CGRect(x: sender.frame.origin.x + sender.frame.size.width - 200 , y: sender.frame.origin.y + sender.frame.size.height, width: 200, height: 200))

Upvotes: 0

IOS Singh
IOS Singh

Reputation: 617

Please use this,

sideSubView = SideView(frame: CGRect(x: sender.frame.origin.x - 200 ,y: sender.frame.origin.y + 40,width: 200,height: 200))

Upvotes: 1

Related Questions