尽管位于Superview的位置,但仍然位于MainScreen中心的UIView中心

时间:2016-06-13 07:51:38

标签: ios objective-c uiview superview

我有一个可以拖动的uiview。在那个UIView我有一个子视图,我希望在设备屏幕的中心高度和宽度。但是,我尝试过以超级视图为中心。我怎么能认为子视图始终位于UIDevice MainScreen的中心,尽管UIView在哪里。

我有(因为长达50000行而被剥离):

    popArtwork = [UIImageView new];
    popArtwork.frame = CGRectMake(367, 367, WidgetWidth, WidgetWidth/5.3);

    popArtwork.layer.cornerRadius = 10;
    popArtwork.layer.masksToBounds = YES;
    popArtwork.alpha = 0;
    [popArtwork setUserInteractionEnabled:YES];
    [add addSubview:popArtwork];

添加是我的超级视图。我的程序有点不寻常,因为它是用户主屏幕(越狱调整)的音乐小部件,所以他们可以将它移动到任何地方。我希望视图popArtwork始终位于屏幕的中心,尽管Add可能在哪里。

1 个答案:

答案 0 :(得分:0)

我不知道它是否适合您,但是当重新定位超级视图时,如何将子视图集中在一起:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(paned:)];
    [_add addGestureRecognizer:pan];

}


-(void)paned:(UIPanGestureRecognizer *)pan{

    CGPoint translatedPoint = [(UIPanGestureRecognizer*)pan translationInView:self.view];

    if ([(UIPanGestureRecognizer*)pan state] == UIGestureRecognizerStateBegan) {
        firstX = [[pan view] center].x;
        firstY = [[pan view] center].y;
    }

    translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);

    [[pan view] setCenter:translatedPoint];


    CGRect newSubviewFrame = _subview.frame;
    newSubviewFrame.origin.x = [UIScreen mainScreen].bounds.size.width/2.0 - newSubviewFrame.size.width/2.0 - _add.frame.origin.x;
    newSubviewFrame.origin.y = [UIScreen mainScreen].bounds.size.height/2.0 - newSubviewFrame.size.height/2.0 - _add.frame.origin.y;
    _subview.frame = newSubviewFrame;

}