Where to get frame size of custom UIView in its subclass

China☆狼群 提交于 2019-12-03 02:02:07
func viewWillAppear(_ animated: Bool)

This is called on the viewController after the view hierarchy is in place and the geometry is set up.

It is usually the best place to arrange geometry-dependent viewController code, and is called just before transition animations are run.

It is followed by a call to viewDidAppear which is called after transition animations have completed.

update

as you want to set this directly in a custom view (rather than in the viewController) the appropriate UIView function to override is layoutSubviews. Be sure to call super.layoutSubviews() in the override.

override func layoutSubviews() {
    super.layoutSubviews()
    //self.frame will be correct here
}

This will be called after the viewController's viewWillAppear and before viewDidAppear

update 2: collectionView cells Collection view cells get their frame data from the collectionview's layout. When a cell needs to know it's geometry, you can override applyLayoutAttributes

func applyLayoutAttributes(_ layoutAttributes: UICollectionViewLayoutAttributes!)

One of the default layoutAttributes is the frame property. See also my comment below on how to extract the frame directly from collectionView.layout.

Since viewDidLayoutSubviews() is getting called multiple times, I'd recommend using the viewDidAppear() delegate.

viewDidLoad() is called before any frame was set.

viewDidLayoutSubviews() is called during frame sizing and will be called multiple times with different frame sizes (usually frameZero before a frame is calculated).

viewDidAppear() All frames are set.

You should have an IBOutlet to your UIView and in the viewDidLayoutSubviews() method, get the size by yourViewOutlet.frame.size.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!