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

后端 未结 2 1695
走了就别回头了
走了就别回头了 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 
    @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];
    }
    

提交回复
热议问题