Попытка настроить UILabel для перемещения в случайные точки на экране - PullRequest
1 голос
/ 06 февраля 2011

Итак, я пытаюсь установить UILabel или фрагмент изменяемого текста, чтобы он перемещался в разные точки на экране через заданные интервалы. Я собираюсь использовать таймер для интервалов, но на самом деле я понятия не имею, как переместить метку. Ищу кого-то, чтобы указать мне в правильном направлении. Вся помощь очень ценится.

Ответы [ 3 ]

4 голосов
/ 06 февраля 2011

Зависит, хотите анимацию?

Если вы не хотите анимировать движение, это так же просто, как изменить его центральную точку

UILabel* label; //Previously initialized UILabel
float newX = 90.0f;
float newY = 101.0f;

label.center = CGPointMake(newX, newY);

Если вы хотите анимировать движение, добавьте блок анимации:

UILabel* label; //Previously initialized UILabel
float newX = 90.0f;
float newY = 101.0f;

[UIView transitionWithView:label
                  duration:0.5f 
                   options:UIViewAnimationCurveEaseInOut
                animations:^(void) {
                     label.center = CGPointMake(newX, newY);
                } 
                completion:^(BOOL finished) {
                     // Do nothing
                }]; 

EDIT:

Начиная с iOS 4, рекомендуемый подход для анимации - это блочные методы . Например:

transitionFromView:toView:duration:options:completion: и transitionWithView:duration:options:animations:completion:

Эти методы доступны только в iOS 4+, поэтому, если вам нужно нацелиться на что-либо раньше, вам придется использовать другие методы, описанные в UIView Class Reference .

Только из личного опыта, использование blocks анимаций на основе значительно упрощает ваш код, делает его менее похожим на спагетти со всеми методами делегатов, которые в противном случае пришлось бы реализовывать для обратных вызовов и т. Д. Блоки действительно очень мощные и очень стоит потратить время на использование.

2 голосов
/ 11 марта 2013

Вы можете перетащить метку, определив класс для перетаскивания метки, и, установив для этого свойства класса значение UILabel, вы можете легко перетащить эту метку в любое место на экране.

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
  {
NSLog(@"touches began");
// Retrieve the touch point
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;

[[self superview] bringSubviewToFront:self];
CGRect f1=[self frame];

//Top Line
line1=[[UIView alloc] initWithFrame:CGRectMake(-500, f1.origin.y, 1300, 1)];
line1.backgroundColor=[UIColor colorWithRed:0 green:0 blue:1.0f alpha:.30f];
[[self superview] addSubview:line1];

//Bottom Line
line2=[[UIView alloc] initWithFrame:CGRectMake(-500, f1.origin.y+f1.size.height, 1300, 1)];
line2.backgroundColor=[UIColor colorWithRed:0 green:0 blue:1.0f alpha:.30f];
[[self superview] addSubview:line2];


//front Line
line3=[[UIView alloc] initWithFrame:CGRectMake(f1.origin.x, -500, 1,1300)];
line3.backgroundColor=[UIColor colorWithRed:0 green:0 blue:1.0f alpha:.30f];
[[self superview] addSubview:line3];

//Rear Line
line4=[[UIView alloc] initWithFrame:CGRectMake(f1.origin.x+f1.size.width,-500, 1, 1300)];
line4.backgroundColor=[UIColor colorWithRed:0 green:0 blue:1.0f alpha:.30f];
[[self superview] addSubview:line4];
   }

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
   {
NSLog(@"touches moved");
// Move relative to the original touch point
CGPoint pt = [[touches anyObject] locationInView:self];
CGRect frame = [self frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;

if(frame.origin.x < 0) {
    frame.origin.x= 0;

}

else if((frame.origin.x+ frame.size.width) > 380) {

    frame.origin.x = 380-frame.size.width;
}

if(frame.origin.y < 0) {

    frame.origin.y= 0;
}

else if((frame.origin.y + frame.size.height) > 280) {

    frame.origin.y = 280-frame.size.height;
}


//Top Line
CGRect frameLine = [line1 frame];
frameLine.origin.x = -500;
frameLine.origin.y =frame.origin.y;
[line1 setFrame:frameLine];


//Bottom Line
frameLine = [line2 frame];
frameLine.origin.x = -500;
frameLine.origin.y = frame.origin.y + frame.size.height;
[line2 setFrame:frameLine];


//front Line
frameLine = [line3 frame];
frameLine.origin.x= frame.origin.x;
frameLine.origin.y= -500;
[line3 setFrame:frameLine];

//Rear Line
frameLine = [line4 frame];
frameLine.origin.x=frame.origin.x+frame.size.width;
frameLine.origin.y= -500;
[line4 setFrame:frameLine];

[self setFrame:frame];
    }
    -(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

[line1 removeFromSuperview];


[line2 removeFromSuperview];


[line3 removeFromSuperview];


[line4 removeFromSuperview];

    }   

После установки свойства типа класса dragLabel при прикосновении к метке перетащите его, и будут вызваны все соответствующие методы делегата.

0 голосов
/ 06 февраля 2011

Просто сделайте:

[myLabel setFrame:CGRectMake(/*x location*/, /*y location*/, /*width*/, /*height*/)];

, и анимация может быть сделана так:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.75];
// whatever you want animated
[UIView commitAnimations];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...