视图在 swift 中显示其外部的子视图

View shows sub view outside of it in swift

在 swift 中,当您定义带有框架的视图并向其中插入子视图(例如标签)时,即使子视图位于视图框架之外,也会显示该子视图。我怎样才能确保视图只显示框架中的子视图? (我想要的原因是我想用子视图为视图设置动画并使其消失但子视图保留)

设置clipsToBounds = true。默认值为 false ,这意味着子视图不会被裁剪。请注意,这样做会导致性能损失很小,因为它需要额外的合成。

根据 documentation:

Setting this value to true causes subviews to be clipped to the bounds of the receiver. If set to false, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value is false.

您应该将 clipToBounds 设置为 true。 属性 决定子视图是否限制在视图的边界内。