With autolayout, label position is reset when I change label text

后端 未结 2 1694
走了就别回头了
走了就别回头了 2020-12-19 17:56

I am developing a very simple application in Objective-c.
In the app, the user can change a position of the label by dragging the screen.

Tap & drag the scre

相关标签:
2条回答
  • 2020-12-19 18:40

    Solution by OP.

    Constraint can be treated as an IBOutlet on Storyboard:
    Associating constraints as well as label or other IBOutlet.

    // ViewController.h
    #import <UIKit/UIKit.h>
    @interface ViewController : UIViewController {
        IBOutlet UILabel *label;
        IBOutlet NSLayoutConstraint *lcLabelTop;
    }
    
    @end
    
    // ViewController.m
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        [self.view addGestureRecognizer:pan];
    }
    
    - (void)panAction : (UIPanGestureRecognizer *)sender
    {
        CGPoint pan = [sender translationInView:self.view];
        lcLabelTop.constant += pan.y;
    
        if (sender.state == UIGestureRecognizerStateEnded) {
            label.text = [NSString stringWithFormat:@"y = %f", lcLabelTop.constant];
        }
    
        [sender setTranslation:CGPointZero inView:self.view];
    }
    
    0 讨论(0)
  • 2020-12-19 18:45

    You cannot use auto layout and change the center / frame of things; those are opposites. Do one or the other - not both.

    So, you don't have to turn off auto layout, but if you don't, then you must use auto layout, and auto layout only, to position things.

    When you move the label, do not change its center - change its constraints. Or at least, having changed its center, change its constraints to match.

    Otherwise, when layout occurs, the constraints will put it back where you have told them to put it. And layout does occur when you change the text, and at many other times.

    0 讨论(0)
提交回复
热议问题