【问题标题】:Why `childView.convert(childView.bounds, to: parentView)` is not equal to `childView.frame` for UIPickerTableViewWrapperCell?为什么`childView.convert(childView.bounds, to: parentView)` 不等于 UIPickerTableViewWrapperCell 的`childView.frame`?
【发布时间】:2022-01-23 02:35:22
【问题描述】:

根据我的理解,frame 是使用父视图坐标系的视图的位置和大小,bounds 是使用自己的坐标系的视图的位置和大小,这意味着childView.convert(childView.bounds, to: parentView) 应该等于childView.frame

但是我发现UIPickerTableViewWrapperCell不是这样,从图中可以看出,frame是(origin = (x = 0, y = 160032.44775782057), size = (width = 134, height = 30.248210824676789)),而convert(bounds, to: parentView)(origin = (x = -71.984082796011151, y = 160032.44585526528), size = (width = 134.04199076956854, height = 29.70736933068838))

为什么这两个值不同?

【问题讨论】:

  • 您是否尝试打印单元格的边界?边界的原点并不总是等于 0,0
  • 嗨 @arturdev,刚刚打印出来,它是 (0, 0),(origin = (x = 0, y = 0), size = (width = 134, height = 32))

标签: ios uikit


【解决方案1】:

经过一番挖掘,我找到了an instructive article,这可能有助于您理解为什么会出现这种看似差异。

为了以后避免断链,我会在下面添加场景。

作者首先以一个在屏幕上绘制的矩形为例。他们使用以下函数打印出框架和边界值:

private func printAll() {
    print("=========================")
    print("X : ", self.orangeView.frame.origin.x)
    print("Y : ", self.orangeView.frame.origin.y)
    print("width : ", self.orangeView.frame.size.width)
    print("height : ", self.orangeView.frame.size.height)
    print("=========================")
    print("X : ", self.orangeView.bounds.origin.x)
    print("Y : ", self.orangeView.bounds.origin.y)
    print("width : ", self.orangeView.bounds.size.width)
    print("height : ", self.orangeView.bounds.size.height)
    print("=========================")
}

使用这个,它们最初以相等的宽度和高度开始:

=========================
X :  87.0
Y :  384.0
width :  240.0
height :  128.0
=========================
X :  0.0
Y :  0.0
width :  240.0
height :  128.0
=========================

然后他们对矩形执行变换以旋转它:

self.orangeView.transform = CGAffineTransform(rotationAngle: 5)

这当然会导致元素的高度和宽度在父 (.frame) 范围内发生变化:

=========================
X :  111.58938416597198
Y :  314.7747071707769
width :  190.82123166805604
height :  266.45058565844624
=========================
X :  0.0
Y :  0.0
width :  240.0
height :  128.0
=========================

这样做的原因当然是通过旋转绘制的矩形,框架矩形的大小发生了变化,即使绘制的矩形没有改变尺寸。 Apple 也完全了解这一点 as indicated in their documentation,声明如下:

警告

如果变换属性不是恒等变换,则该属性的值是未定义的,因此应该被忽略。

这很重要,因为我们可以从您提供的数据中推断出一些重要的行为。具体来说,如果我们忽略坐标而查看高度和宽度值,我们会看到以下差异:

frame:   (width = 134, height = 30.248210824676789)
bounds:  (width = 134, height = 32)
convert: (width = 134.04199076956854, height = 29.70736933068838)

查看图像中的 UI 元素本身,我们甚至可以看到垂直“挤压”的文本,这表明这些元素很可能以某种方式应用了变换。这可能导致 Apple 文档中指出的上述未定义行为。正如 Apple 在其文档中指出的那样,当变换属性不是身份变换时,应忽略该属性的值。

不幸的是,我们无法验证这是问题的原因,因为UIKit,据我从挖掘中得知,不共享它的源代码,但导致未定义行为的转换似乎是我们最好的解释可以合理到达。

【讨论】:

    猜你喜欢
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多