如何使用UIScrollview contentoffset iOS保持UIView中心?

时间:2019-04-10 11:30:52

标签: ios objective-c uiscrollview

我在UIView内有UIScrollView,其中包含4个子视图。在点击子视图时,我要调整滚动视图的contentoffset属性,以使我点击的subview与屏幕中心对齐。

我尝试了一些逻辑,但是工作不正常。

-(void)onDragViewTapped:(UITapGestureRecognizer *)recognizer
{
    CGFloat width = self.scrollVw.contentSize.width/2;
    CGFloat vwWidth = recognizer.view.frame.size.width/2;
    width = width - vwWidth - vwWidth/self.scrollVw.zoomScale - 
    width/self.scrollVw.zoomScale;

    CGFloat height = self.scrollVw.contentSize.height/2;
    CGFloat vwHeigh = recognizer.view.frame.size.height/2;
    height = height- vwHeigh -  vwHeigh/self.scrollVw.zoomScale - 
    height/self.scrollVw.zoomScale;

    [self.scrollVw setContentOffset:CGPointMake(width, height) 
    animated:YES];
}

2 个答案:

答案 0 :(得分:1)

这对我有用(实际上没有缩放):

// This view below here is the view of the view controller, 
// use the container view instead to align the center to
let newX = tappedView.center.x - view.center.x
let newY = tappedView.center.y - view.center.y
scrollview.setContentOffset(CGPoint(x: newX, y: newY), animated: true)

答案 1 :(得分:0)

根据Apple文档,在视图坐标系之间进行转换

将点从接收者的坐标系转换为指定视图的坐标。

  • func convert(CGPoint,to:UIView?)-> CGPoint

将点从给定视图的坐标系转换为接收者的坐标系。

  • 功能转换(CGPoint,来自:UIView?)-> CGPoint

将矩形从接收者的坐标系转换为另一个坐标系    视图。

  • 功能转换(CGRect,至:UIView?)-> CGRect

将矩形从另一个视图的坐标系转换为接收者的坐标系。

  • 功能转换(CGRect,来自:UIView?)-> CGRect

我认为这会对您有所帮助。