且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自定义 UIView 的子视图 x 帧位置错误

更新时间:2023-11-10 10:11:22

init 中的设置肯定会提供 self.frame/self.bounds无论视图的初始化值是什么,在视图层次结构中布局时都不是正确的最终值.处理这个问题的***方法可能就像您尝试过的那样,在 init 中添加视图,并使用属性来保持对它们的引用(您已经这样做了),然后在 -layoutSubviews()中设置框架代码>.

It's definitely the case that the setting up in init will provide self.frame/self.bounds values for whatever the view's initialized values are and not the correct final values when laid out in the view hierarchy. Probably the best way to handle this is like you tried, to add the views in init, and use property to keep a reference to them (you already are doing this) and then set the frame in -layoutSubviews().

它可能在 -layoutSubviews() 中不起作用的原因是对于创建后的每个视图,您需要调用 .translatesAutoresizingMaskIntoConstraints = false.否则,对于以编程方式创建的视图,系统将在作为子视图添加时为值创建约束,覆盖任何框架设置.尝试设置它,看看它是如何进行的.

The reason it probably didn't work in -layoutSubviews() is for each view after creation you need to call .translatesAutoresizingMaskIntoConstraints = false. Otherwise with programmatically-created views the system will create constraints for the values when added as a subview, overriding any setting of frames. Try setting that and see how it goes.

为了调整 CAShapeLayer 的大小,而不是作为子层添加(这需要手动调整大小),因为 AnimationCirleView 视图是专门的,该视图可以由 CAShapeLayer 支持.请参阅 在 swift 中覆盖 UIView 中的默认图层类型 中的答案

For resizing the CAShapeLayer, instead of adding as a sublayer (which would require manually resizing) since AnimationCirleView view is specialized the view can be backed by CAShapeLayer. See the answer at Overriding default layer type in UIView in swift