视图不会粘在上面(不会改变位置)

时间:2016-09-17 13:26:25

标签: ios swift uiview uiscrollview uikit

我试图在滚动的同时将UIView粘在上面。尝试使用stackOverflow上建议的max(x:T,y:T)方法,但它不起作用。我设法检测何时应该重新定位scrollView,但更新帧没有任何影响。

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate{

@IBOutlet var objectView: UIView!
@IBOutlet var scrollView: UIScrollView!

//var originalOffsetY : CGFloat!
//var originalOffestX : CGFloat!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let size = CGSize.init(width: self.view.frame.width, height: self.view.frame.height*2)
    scrollView.contentSize = size
    scrollView.backgroundColor = UIColor.blueColor()
    objectView.backgroundColor = UIColor.whiteColor()
    scrollView.delegate = self

    scrollView.addSubview(objectView)
}

    // override func viewWillAppear(animated: Bool) {
    // originalOffsetY = objectView.frame.origin.y
    // originalOffestX = objectView.frame.origin.x

    // } 


func scrollViewDidScroll(scrollView: UIScrollView) {

    print("ScrollView \(scrollView.contentOffset.y)")
    print("ObjectView \(objectView.frame.origin.y)")


    let location = CGPointMake(0, scrollView.contentOffset.y)
    let size = objectView.frame.size


    if scrollView.contentOffset.y >= objectView.frame.origin.y {
        objectView.frame = CGRect.init(origin: location, size: size)
        print("Detected \(objectView.frame)")

    }

    //        var newRect = objectView.frame
    //        newRect.origin.y = max(originalOffsetY!, scrollView.contentOffset.y)
    //        objectView.frame = newRect


}

}

条件匹配成功,如Logs中所示。但观点保持不变。我要求objectView滚动一下......从y = 270到0左右但不超出它。

1 个答案:

答案 0 :(得分:0)

您需要在滚动视图中跟踪视图的原始位置,并使用该值进行计算,这是一个非常简单的示例:

class StickyScrollViewController: UIViewController {

    var stickyView = UIView(frame: CGRect(x: 0, y: 100, width: 300, height: 100))
    var originalStickyOrigin: CGPoint = CGPoint(x: 0, y: 100)

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        var nextYOffset = max(originalStickyOrigin.y, scrollView.contentOffset.y)
        stickyView.frame = CGRect(x: 0, y: nextYOffset, width: 300, height: 100)
    }
}