对不起标题,我只是不知道怎么称呼它。
我想让我的scrollView能够从顶部或底部滚动,直到中心的圆圈,就像LinkedIn一样:
因此,您可以将图像滚动到中心的圆圈。如何改进我的代码,实现这一目标?
我的代码是:
scrollView!.delegate = self
imageView.frame = CGRectMake(0, 0, (scrollView?.frame.width)!, (scrollView?.frame.height)!)
if let validImage = self.avatarImage {
self.imageView.image = validImage
imageView.contentMode = .ScaleAspectFill
imageView.frame = avatarImageFrame!
}
imageView.userInteractionEnabled = true
scrollView?.addSubview(imageView)
scrollView?.contentSize = (avatarImage?.size)!
let scrollViewFrame = scrollView?.frame
let scaleWidth = (scrollViewFrame?.size.width)! / (scrollView?.contentSize.width)!
let scaleHeight = (scrollViewFrame?.size.height)! / (scrollView?.contentSize.height)!
let minScale = min(scaleHeight, scaleWidth)
scrollView?.minimumZoomScale = minScale
scrollView?.maximumZoomScale = 1
scrollView?.zoomScale = minScale
centerScrollViewContents()
}
func centerScrollViewContents() {
let boundsSize = scrollView?.bounds.size
var contentsFrame = imageView.frame
if contentsFrame.size.width < boundsSize?.width {
contentsFrame.origin.x = ((boundsSize?.width)! - contentsFrame.size.width) / 2
} else {
contentsFrame.origin.x = 0
}
if contentsFrame.size.height < boundsSize?.height {
contentsFrame.origin.y = ((boundsSize?.height)! - contentsFrame.size.height) / 2
} else {
contentsFrame.origin.y = 0
}
contentsFrame.size.height = UIScreen.mainScreen().bounds.height
imageView.frame = contentsFrame
}
func scrollViewDidZoom(scrollView: UIScrollView) {
centerScrollViewContents()
}
答案 0 :(得分:0)
有很多方法可以实现这一目标。滚动视图的最佳效果可能是将滚动视图的框架设置为与圆框架相同。内容大小应该仍然与背景(或者更确切地说是您的图像中的图像)相同,并且当您第一次进入屏幕时,应设置内容偏移以使图像位于中心。
所以到现在为止你可以想象一个圆圈后面的小滚动视图,但背景的其余部分却丢失了。要解决这个问题,您需要做的就是在滚动视图上禁用绑定剪切,默认情况下设置为true。因此将“剪辑子视图”设置为false。
现在你已经可以看到整个图像并且弹跳是正确的,以便始终将图像保持在圆圈内,但还有一件事缺失。由于滚动视图实际上非常小,您可以看到您可能无法在其框架外与其进行交互。这是一种自然行为,可以通过覆盖名为hitTest
的方法来更改。此方法将返回应收集交互的视图。所以我们需要子类化滚动视图的超级视图:
无论你在界面构建器或代码中的哪个位置执行此操作,我都希望您有一些视图(将其称为背景),其中包含滚动视图(小视图)和叠加(带圆圈的视图)。背景必须是子类,并且引用滚动视图。然后简单地覆盖命中测试方法,如下所示:
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
var myFrame = frame
myFrame.origin = CGPointZero // maybe this should be commented out
if CGRectContainsPoint(myFrame, point) {
return scrollView
} else {
return super.hitTest(point, withEvent: event)
}
}
通过这样做,滚动视图可以在背景中的任何位置进行交互,整个图像在背景上可见,图像将始终在圆圈内。
祝你好运。