UIAnimation - Показать UIView от button.frame.origin.y - PullRequest
0 голосов
/ 27 февраля 2012

У меня есть UIButton где-то на мой взгляд. При касании события кнопки I появляется UIView. UIAnimation, который я использовал, отображает вид сверху окна. Но я хочу, чтобы это появилось на button.frame.origin.y. До нажатия кнопки вид не виден. При прикосновении к кнопке вид должен начать появляться сверху позиции.

Вот код:

-(IBAction) ShowInfowView:(id)sender{

    CGRect rect = viewInfo.frame;

    rect.origin.y = rect.size.height - rect.size.height+58.0;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.70];
    [UIView setAnimationDelay:0.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

    viewInfo.frame = rect;

    [UIView commitAnimations];

}

Вот как я снова скрываю вид:

-(IBAction) HideInfoView:(id)sender{

    CGRect rect = viewInfo.frame;

    rect.origin.y = -rect.size.height;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.70];
    [UIView setAnimationDelay:0.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

    viewInfo.frame = rect;

    [UIView commitAnimations];

}

В viewDidLoad я делаю следующее:

CGRect rect = viewInfo.frame;
rect.origin.y = -rect.size.height;
viewInfo.frame = rect;  

ОБНОВЛЕНИЕ :

Пожалуйста, посмотрите этот пример. Здесь вид появляется сверху экрана. Я хочу, чтобы это появилось от оси Y кнопки. В связи с этим, пожалуйста, рассмотрите положение кнопки y немного вверх.

Ответы [ 4 ]

2 голосов
/ 29 февраля 2012

Я сделал именно то, что вы пытаетесь в моем недавнем проекте.Следующие шаги должны сделать эту работу: 1. В вашем viewDidLoad: вы начинаете свой viewToFadeIn следующим образом:

viewToFadeIn = [[UIView alloc] initWithFrame:CGRectMake(20,self.view.frame.size.height+10, self.view.frame.size.widh-40, 200)]; 

//its important to initalize it outside your view
//your customization of this view
[self.view addSubview:viewToFadeIn];

2.your ShowInfowView: Метод должен выглядеть следующим образом:

`- (IBAction) ShowInfowView: (id) отправитель {

[UIView beginAnimations:@"fadeIn" context:NULL];
[UIView setAnimationDuration:0.25]; 
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
viewToFadeIn.transform = CGAffineTransformMakeTranslation(0, -290);
//290 is in my case, try a little for your correct value
[UIView commitAnimations];

} 3.your HideInfoView:` Метод выглядит следующим образом

-(IBAction) HideInfoView:(id)sender{
[UIView beginAnimations:@"fadeOut" context:NULL];
[UIView setAnimationDuration:0.25]; 
[UIView setAnimationDelegate:self];
viewToFadeIn.transform = CGAffineTransformMakeTranslation(0, 0);
[UIView commitAnimations];
}

РЕДАКТИРОВАТЬ: 4. animationFinishedMethod:

- (void)animationFinished:(NSString *)animationID finished:(BOOL)finished context:(void *)context{ 
   if ([animationID isEqual:@"fadeIn"]) { 
      //Do stuff 
   } 
   if ([animationID isEqual:@"fadeOut"]) { 
      //Do stuff 
   } 
}

СМОТРЕТЬ ЭТО

Это должно сработать.Удачи

2 голосов
/ 27 февраля 2012

То есть, вы хотите эффект слайда, но не сверху экрана, просто какое-то произвольное значение?

Один из способов сделать это:

1) Вы должны создатьпредставление, которое имеет размеры и положение желаемого вида ПОСЛЕ окончания анимации, мы назовем его baseview .

2) Установите это baseview свойство clipsToBounds до ДА .Это сделает невидимыми все подпредставления, находящиеся за пределами baseview .

3) Добавьте анимационный вид в качестве подпредставления baseview , но установитекадр, так что он невидим (поместив его выше baseview ):

frame = CGRectMake(0, -AnimViewHeight, AnimViewWidth, AnimViewHeight);

4) Анимируйте кадр animview:

//put this inside of an animation block
AnimView.frame = CGRectMake(0, 0, AnimViewWidth, AnimViewHeight);

РЕДАКТИРОВАТЬ:

Пример:

//define the tags so we can easily access the views later
#define BASEVIEW_TAG 100
#define INFOVIEW_TAG 101

- (void) showInfo
{
        //replace the following lines with preparing your real info view
        UIView * infoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        [infoView setBackgroundColor: [UIColor yellowColor]];
        [infoView setTag: INFOVIEW_TAG];

        //this is the frame of the info view AFTER the animation finishes (again, replace with real values)
        CGRect targetframe = CGRectMake(100, 100, 100, 100);

        //create an invisible baseview
        UIView * baseview = [[UIView alloc] initWithFrame:targetframe];
        [baseview setBackgroundColor: [UIColor clearColor]];
        [baseview setClipsToBounds: YES]; //so it cuts everything outside of its bounds
        [baseview setTag: BASEVIEW_TAG];

        //add the nfoview to the baseview, and set it above the bounds frame
        [baseview addSubview: infoView];
        [infoView setFrame:CGRectMake(0, -infoView.bounds.size.height,
                                      infoView.bounds.size.width, infoView.bounds.size.height)];

        //add the baseview to the main view
        [self.view addSubview: baseview];

        //slide the view in
        [UIView animateWithDuration: 1.0 animations:^{
            [infoView setFrame: baseview.bounds];
        }];

        //if not using ARC, release the views
        [infoview release];
        [baseview release];
}

- (void) hideinfo
{
        //get the views
        UIView * baseView = [self.view viewWithTag: BASEVIEW_TAG];
        UIView * infoView = [baseView viewWithTag: INFOVIEW_TAG];

        //target frame for infoview - slide up
        CGRect out_frame = CGRectMake(0, -infoView.bounds.size.height,
                                      infoView.bounds.size.width, infoView.bounds.size.height);

        //animate slide out
        [UIView animateWithDuration:1.0
                         animations:^{
                             [infoView setFrame: out_frame];
                         } completion:^(BOOL finished) {
                             [baseView removeFromSuperview];
                         }];
    }
1 голос
/ 27 февраля 2012

Ваша проблема не ясна (для меня). Что это?

rect.origin.y = rect.size.height - rect.size.height+58.0;

Является ли 58 происхождение вашего UIButton?

Вы должны использовать sender.frame и т. Д.

Используйте блоки для анимации, как это

[UIView animateWithDuration:0.5f animations:^{
    // Animation here
} completion:^(BOOL finished) {
    // onComplete
}];
0 голосов
/ 29 февраля 2012
- (void) slideIn{
    //This assumes the view and the button are in the same superview, if they're not, you'll need to convert the rects
    //I'm calling the animated view: view, and the button: button...easy enough
    view.clipToBounds = YES;
    CGRect buttonRect = button.frame;
    CGRect viewRect = CGRectMake(buttonRect.origin.x, buttonRect.origin.y + buttonRect.size.height, view.bounds.size.width, 0);
    CGFloat intendedViewHeight = view.height;
    view.frame = viewRect;
    viewRect.size.height = intendedViewHeight;
   [UIView animateWithDuration:.75 delay:0.0f options:UIViewAnimationOptionCurveEaseOut animations:^{
        view.frame = viewRect;
    }completion:nil];
}

Это приведет к тому, что вид будет выдвигаться из-под кнопки.Чтобы вернуть вид назад, вы просто переворачиваете анимацию.Если вы хотите сдвинуть ее вверх с кнопки, вам необходимо убедиться, что начальное значение y соответствует значению кнопки y (а не y и высота) и анимировать как высоту, так иy значения вида, который нуждается в анимации.

...