簡體   English   中英

使用約束旋轉視圖-Swift

[英]Rotating view using constraints - Swift

我正在嘗試使用約束在另一個視圖之上旋轉uiview。 這是我實現的

mediaContainer.addSubview(overlayView)
keepBottomLeft()
overlayView.layoutIfNeeded()

func keepBottomLeft(overlayView: UIView) {
    NSLayoutConstraint(item: overlayView, attribute:.width, relatedBy:.equal,toItem: mediaContainer, attribute:.width, multiplier: 0.8, constant: 0).isActive = true
    NSLayoutConstraint(item: overlayView, attribute:.leading, relatedBy:.equal, toItem: mediaContainer, attribute:.leading, multiplier: 1, constant: 0).isActive = true
    NSLayoutConstraint(item: overlayView, attribute:.height, relatedBy:.equal,toItem: nil, attribute:.notAnAttribute, multiplier: 1.0, constant: 26).isActive = true
    NSLayoutConstraint(item: overlayView, attribute:.bottom, relatedBy:.equal, toItem: mediaContainer, attribute:.bottom, multiplier: 1, constant: 0).isActive = true
    overlayView.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))
}

是否需要使用錨點? 這是我要實現的目標?

從視圖A

查看B

我得到的是

有人可以指出我正確的方向嗎?

您的錨點位於黃色視圖的中心; 默認值。 您可以使用layer.anchorPoint = CGPoint(x:0,y:1)將其移動到左下角[請注意錨點的單位坐標格式為0到1,而不是點數]。 您仍然需要x = height的額外轉換。

或者,您可以連接變換並將中心移動到要旋轉的點,執行旋轉,然后反轉平移(這實際上是使用3d變換的典型方法)。

更新:這是一個操場。 請注意,您以與要應用轉換的相反順序連接矩陣。 我在這里有一個動畫,因此您可以分解變換並查看每個變換的作用:

  1. 將視圖移動到原點(0,0)(這是最后一個變換)
  2. 將視圖順時針旋轉90度
  3. 將視圖上下移動其當前寬度的一半,使其位於超級視圖的底部。

     import PlaygroundSupport import UIKit class V: UIViewController { var overlayView = UIView() override func viewDidLoad() { super.viewDidLoad() overlayView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(overlayView) overlayView.backgroundColor = .yellow overlayView.heightAnchor.constraint(equalToConstant: 26).isActive = true overlayView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8).isActive = true overlayView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true overlayView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true } override func viewDidAppear(_ animated: Bool) { UIView.animate(withDuration: 1) { let center = self.overlayView.center let size = self.overlayView.bounds.size self.overlayView.transform = CGAffineTransform(translationX: self.view.bounds.size.height - size.width / 2, y: -size.height/2) .concatenating(CGAffineTransform(rotationAngle: CGFloat.pi/2) .concatenating(CGAffineTransform(translationX: -center.x, y: -center.y))) } } } let v = V() v.view.frame = CGRect(x: 0, y: 0, width: 200, height: 200) PlaygroundPage.current.liveView = v 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM