gpt4 book ai didi

ios - View 不粘在顶部(不改变位置)

转载 作者:行者123 更新时间:2023-11-30 13:04:34 25 4
gpt4 key购买 nike

我试图在滚动时将 UIView 粘在顶部。尝试使用 max(x:T, y:T) 方法,如 stackOverflow 上建议的那样但它不起作用。我设法检测到何时应该重新定位 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 ..但不能超出它。

最佳答案

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

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)
}
}

关于ios - View 不粘在顶部(不改变位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39547345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com