【问题标题】:Swift: How to position a container view correctly at the bottom in a parent view? (Or: is there another option than a container view?)Swift:如何在父视图的底部正确定位容器视图? (或者:除了容器视图之外还有其他选择吗?)
【发布时间】:2017-10-09 15:29:36
【问题描述】:

我还是 swift 的新手,我想做的是在父视图的底部放置一个容器视图(最初包含的部分将在视图之外)。然后,当用户触摸按钮时,容器会被动画化并向上移动,以便显示所有内容。

动画效果很好,但定位对我来说很难。这是我到目前为止所做的:

@IBOutlet var testView: UIView!
override func viewDidLoad() {
        super.viewDidLoad()

        testView.frame.size = CGSize(width: view.bounds.width, height: 400)
        testView.layer.position = CGPoint(x: view.frame.midX, y: view.frame.maxY + 90)
        view.addSubview(testView)
    }

所以我将容器视图设置为超级视图的宽度和 400 的固定大小。我尝试将它定位在屏幕底部的中心位置,以便它的一部分显示,一部分在屏幕之外。

这里是动画部分:

@IBAction func showMoreButton(_ sender: UIButton) {
    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {self.testView.transform = CGAffineTransform(translationX: 0, y: -190)

    }, completion: nil)

所以在这里我只是将容器向上移动 190。容器底部是一个关闭按钮,没有显示(仍然在超级视图之外)。

我很确定问题在于我如何将视图直接定位在 view.frame.maxY + 90(以便显示 90 像素)相对于它的高度。当我降低视图高度时,容器的原始位置会越来越向下移动,很明显,在动画之后一切都显示出来了,但它太小了。 由于 UIKit 中的原点位于 0,0 的左上角,我现在知道如何将视图定位在超级视图的底部,以便显示大约 90 像素,并且当动画完成时,所有视图都被移动up 并且现在显示在 superview 中。

我该怎么做?

【问题讨论】:

    标签: ios view uiviewcontroller


    【解决方案1】:

    据我了解,您希望获得一个顶部只有一个引导按钮可见的视图。点击按钮后,视图应该向上滑动并显示其全部内容。

    您只需要操作内容的视图框架的 Y 偏移量。

    let contentHeight = CGFloat(250) // Full content height
    let contentOffset = CGFloat(40) // Offset for the lead button
    
    func displayBottomView(offset: CGFloat) {
        redContentView.frame = CGRect(x: 0, y: view.frame.size.height-offset, width: view.frame.size.width, height: contentHeight)
    }
    

    这就是你应该如何配置你的视图控制器。

    override func viewDidLoad() {
        super.viewDidLoad()
        // Set the initial position to show only a button
        displayBottomView(offset: contentOffset) 
    }
    
    @IBAction func redButtonDidTap(_ sender: UIButton) {
        UIView.animate(withDuration: 0.5) {
            // Animate displaying of the full content
            self.displayBottomView(offset: self.contentHeight)
        }
    }
    

    这个可以,但它不是布局操作的好方法。我真的建议您切换到自动布局方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 2016-04-16
      相关资源
      最近更新 更多