1

I am attempting to get a UIButton's y coordinate position through the stack view that it belongs to. I need this value in the program to map the position of the button to a different coordinate system.

Here is my code that will grab the button's y-value from the stack view:

p_tilePosition.x = round(self.layer.position.x / (self.frame.size.width + 8.0))// The 8 here is the standard spacing between sibling views
        let testView = self.superview
        if let yPosition = self.superview?.layer.position.y{
            p_tilePosition.y = round(yPosition / (self.frame.size.height + 8.0))
        }

(Note that this is in a subclass of the UIButton. When the UIButton is inilized, it will run through this code to create the mapping)

However, I have found out that the self.superview is nil. I am confused by this because I thought that the superview of the button is the stack view that the button is in? Is this not the case? How would I be able to get the button's y-position by getting the stack's y-position on initialization?

philm
  • 797
  • 1
  • 8
  • 29

1 Answers1

1

First - there is no any superview while UIButton initialisation. Avoid to do any layout during initialisation. Indeed if it rely on superview or any other components that not belongs to UIView. Better to do layout in viewDidLoad, viewWillLayoutSubviews or viewDidLayoutSubviews of view controller.

Second - if you want to get position of your any of your views converted to coordinates of other view, or main window, you can use UIView.convert( to: ) family. Fo example

let postion = label1.convert(CGPoint.zero, to: nil)

Will give you origin of your button in main window.

!!! Please note that I'm requesting not label1.frame.origin but CGPoint.zero, in label's internal coordinates origin of the label is (0, 0).

(to be honest I should convert label1.bounds.origin, but it is almost always (0,0) )

You can get same result by:

let postion = label1.superview.convert(label1.frame.origin, to: nil)
MichaelV
  • 1,231
  • 8
  • 10
  • Ok so at the initialization routine, the stack view has not assigned the button as a subview. I am not doing any layout at this point. Just trying to set up the data structure for later use. It sounds like I should do the converting after the layout has all been initialized. I think that I can calculate the position at a later point in the program! – philm Jan 05 '18 at 19:24
  • There is few places designated to do it. Please look at https://developer.apple.com/documentation/uikit/uiviewcontroller/1621398-viewdidlayoutsubviews and https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews – MichaelV Jan 08 '18 at 10:42
  • Yes, I found a location within the viewController. the viewDidLoad function. Thank you – philm Jan 08 '18 at 14:25