問題描述
將 UIView.transform 設置為任意翻譯 CGAffineTransform 什麼都不做 (Setting UIView.transform to arbitrary translate CGAffineTransform does nothing)
我有一個名為 container
的 UIView
,我想使用仿射變換來移動(偏移)。此視圖包含 UIImageView
並且是 UICollectionViewCell
的子視圖。
所以應該很簡單:
container.transform = CGAffineTransformMakeTranslation(100, 200) //render container 100 points right and 200 points down
相反這很困難,因為theat 代碼不做任何事情。視圖在同一個地方呈現,就像我刪除那條線一樣。所以我添加了“打印”來驗證設置了哪些仿射翻譯:
container.transform = CGAffineTransformMakeTranslation(100, 200)
print(container.transform) //prints: CGAffineTransform(a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 100.0, ty: 200.0)
看起來沒問題。所以我嘗試用 CGAffineTransformMakeRotation
旋轉 container
視圖 它根據 文檔。我嘗試了平移、旋轉和縮放變換的不同組合,只是發現仿射變換矩陣集沒問題,但屬性 tx
和 ty
似乎被忽略了, a, b, c
和 d
似乎使用不同的錨點然後視圖的中心(不能說那個點是什麼)。
任何想法是什麼原因造成的以及如何解決?
參考解法
方法 1:
There must be something like auto layout messing things up for you. In the absence of outside influence, setting a view's affine transform to CGAffineTransformMakeTranslation(100, 200) will shift it right 100 points and down 200. I verified this by making a new Single View Project in Xcode and changing the viewDidLoad method in the ViewController.swift class to:
override func viewDidLoad()
{
super.viewDidLoad()
view.backgroundColor = UIColor.blueColor();
let container = UIView(frame: CGRectMake(0,0,100,100));
container.backgroundColor = UIColor.greenColor();
container.transform = CGAffineTransformMakeTranslation(100, 200);
view.addSubview(container);
}
As expected this makes the green container view appear 100 points to the right and 200 points down, even though its frame is (0,0,100,100).
So please check for auto layout and other such things that might influence the placement of this view, and if you can't find anything please post more code. Also, if your container view doesn't have a background color, please give it one so that you can see its position directly, instead of deducing its position by looking at the image view.
n.b. Setting a view's transform doesn't actually move the view itself, it just changes how/where it draws its content.