我正在Objective-c中开发一个非常简单的应用程序.
在应用程序中,用户可以通过拖动屏幕来更改标签的位置.
点击并拖动屏幕,标签上下移动以匹配手指的位置.
松开手指时,标签的坐标信息将设置为其文本.
但标签位置在其文本更改时重置.
// IBOutlet UILabel *label - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint touch = [[touches anyObject] locationInView:self.view]; label.center = CGPointMake(label.center.x, touch.y); } - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint touch = [[touches anyObject] locationInView:self.view]; label.center = CGPointMake(label.center.x, touch.y); } - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint touch = [[touches anyObject] locationInView:self.view]; label.text = [NSString stringWithFormat:@"y = %f", touch.y]; }
在touchesEnded事件中,只需更改标签的文本,
但其位置已重置.
我试图改变touchesEnded事件如下,但它没有解决问题.
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint touch = [[touches anyObject] locationInView:self.view]; label.text = [NSString stringWithFormat:@"y = %f", touch.y]; label.center = CGPointMake(label.center.x, touch.y); // add this line }
我想在不取消选中"使用自动布局"的情况下解决这种奇怪的行为.
我想继续使用自动布局.
我的应用程序有4个截图.
4截图
第一张图片是故事板.
我有一个带有自动布局限制的标签.
第二张图片是启动应用程序后的屏幕截图.
第三个图像是用户拖动屏幕,
标签向下移动以匹配手指.
释放手指后,第四张图像就出现
了,标签文字也发生了变化.
matt.. 6
您不能使用自动布局并更改事物的中心/框架; 那些是对立的.做一个或另一个 - 不是两个.
所以,你不必关闭自动布局,但如果你不这样做,那么你必须使用自动布局和自动布局只,到位置的事情.
移动标签时,请勿更改其中心 - 更改其约束.或者至少,改变了它的中心,改变其约束以匹配.
否则,当布局发生时,约束会将它放回到告诉他们放置它的位置.和布局确实当你改变文本出现,以及其他许多倍.