我有一個scrollView在我的ViewController。在scrollView被放置垂直居中,其寬度等于的寬度ViewController和高度等于100。為了使scrollView可滾動,我contentSize為這個 scrollView設定了一個任意值,假設它是(500, 100). 這有助于我的 scrollView 水平滾動。
我的要求是我希望scrollView的內容從scrollView. 因此,我設定contentInset了它的價值。
let halfWidth = scrollView.bounds.size.width / 2.0
scrollView.contentInset = UIEdgeInsets(top: 0, left: halfWidth, bottom: 0, right: halfWidth)
scrollView.contentOffset = CGPoint(x: -halfWidth, y: 0)
請記住,我的scrollView寬度等于ViewController寬度。因此,halfWidth上面代碼中的值將與view.bounds.width / 2.0.
它的作業原理
在 iPhone 12 Pro 中,資料值如下所示:
ViewController/ 螢屏 /scrollView寬度 =390halfWidth=195scrollView.contentOffset.x=-195
根據我們在代碼中的計算,上述所有值都證明是絕對正確的。
它不起作用的地方
在 iPhone 12 mini 中,資料值如下所示:
ViewController/ 螢屏 /scrollView寬度 =375halfWidth=187.5scrollView.contentOffset.x=-187.33333333333334
的值scrollView.contentOffset.x是預期的-187.5,但實際上是-187.33333333333334。
使用所有其他設備進一步觀察
在觀察模式時,我意識到 contentOffset 值的這種邊際誤差出現在滿足以下兩個條件的特定設備上:
- 條件 1:設備寬度為奇數。
- 條件 2:設備比例因子為奇數。
重現錯誤的示例設備 - iPhone 12 mini、11 Pro、X、XS。所有這些設備都有螢屏寬度375和比例因子3。
為什么精度很重要
My usecase is that I am creating a custom slider using UICollectionView which is responsible to emit the value / fraction of sliding based on the amount of scroll that has taken place. In the question details that I have mentioned above, the scenario is for the case where no scrolling has taken place and hence my expectation of the value / fraction emitted is 0. But, because of this marginal error, the value turns out to be non-zero every time the user tries to scroll it to the beginning.
Is this a known bug? Is there any work around for this?
I have created an example project for quick debugging. You can clone it from here.
uj5u.com熱心網友回復:
作業系統會將您的控制元件置于偶數像素邊界上。
您正在 UI 空間中定位您的控制元件。因此,系統會將您提供的坐標轉換為像素空間,設定控制元件的位置(在像素邊界上),但在 UI 空間中將位置回傳給您。
所以它需要你在 UI 空間中的偏移量并將其轉換為像素空間:
偏移 * 螢屏比例 = 像素偏移
187.5 * 3 = 562.5 像素
但像素是真實的、物理的東西。沒有半像素這樣的東西。因此系統四舍五入,像素偏移量變為 562 像素。
當您將該偏移量轉換回 UI 空間時
像素偏移/螢屏比例 = ui 空間偏移
562 / 3 = 187.3333...
這就是系統為您返還該價值的原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334838.html
