我创建了一个标签,现在我想改变它在屏幕上的显示位置,那么我该如何以编程方式做到这一点?
当我第一次启动它时,我的屏幕看起来像这样。
但我想在它第一次打开时显示它。
将其从视图中移除。然后更改 UIlabel 的框架。然后将其添加到视图中。
[yourLabel removeFromSuperView];
temp.frame=CGRectMake(x,y,width,height); //set the frame as you want
[self.view addSubView:yourLabel];
您应该修改标签的frame
属性。它的类型CGRect
:
struct CGRect {
CGPoint origin;
CGSize size;
};
要更改其位置,请更改origin
点值。它对应于标签的左上角。
CGRect labelFrame = [label frame];
labelFrame.origin.x = 50; // set to whatever you want
labelFrame.origin.y = 100;
[label setFrame:labelFrame];
//simply you change origin for label
//it make animation for moving label in the view
-(void)your_action
{
[UIView animateWithDuration:2
delay:1.0
options: UIViewAnimationCurveEaseOut
animations:^{
label.frame=CGRectMake(0, 0, width, height);
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
}
//此代码用于在视图中拖动标签,在视图中单击标签原点更改为触摸点
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *myTouch = [touches anyObject];
point = [myTouch locationInView:self.view];
[UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationCurveEaseOut
animations:^{
label.frame = CGRectMake(point.x, point.y,width, height);
}
completion:nil];
}
//enable user interaction for label
你说你以编程方式创建标签,所以你必须像这样设置代码:
- (void)viewDidLoad
{
[super viewDidLoad];
yourlabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
yourlabel.text = @"text";
yourlabel.userInteractionEnabled = YES;
[self.view addSubview:alabel];
}
这应该做的工作。