简体   繁体   中英

Center UIView in center of MainScreen Despite Location of Superview

I have a uiview which can be dragged around. In that UIView I have a subview which I want to be centered on the device screen both height and width. But what ever I try it centers the superview. How can I make it that the subview is always at the center of the UIDevice MainScreen despite where the UIView is.

I have (stripped down because its 50000 lines long):

    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];

Add is my superview. My program is a little unusual in the way that it is a music widget for the user's home screen (jailbreak tweak) so they can move it where ever. I want the view popArtwork to always be in the center of the screen despite wherever Add might be.

I don't know if it's what you are looking for, but its how to center a subview when the superview is re-positioned:

- (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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM