简体   繁体   English

iOS Swift-使用滑块移动图像

[英]iOS Swift - moving image with slider

I have some problems moving an UIImageView using a slider. 我在使用滑块移动UIImageView时遇到一些问题。 This is my code I'm currently using: 这是我目前正在使用的代码:

@IBOutlet weak var titanic: UIImageView!

...

let screenWidth = UIScreen.mainScreen().bounds.width
let titanicWidth = titanic.bounds.size.width
let viewcenter = titanicWidth / 2
let slidervalue = CGFloat(sender.value)
let value = (screenWidth * slidervalue * (1.0 - titanicWidth / screenWidth)) + viewcenter
titanic.center.x = CGFloat(value)
print(value)

Actually, I can move the image with this code, BUT: somehow the image always "jumps" back to it's origin position in the middle of the screen, without moving the slider at all... Do you have any idea, how this can happen? 实际上,我可以使用以下代码移动图像,但是:图像总是以某种方式“跳回”到屏幕中间的原点位置,而根本不移动滑块...您有任何想法吗,这怎么办发生? I already checked the inspector on the right for some strange attributes which may cause this effect, but no luck... 我已经在右边的检查器中检查了一些奇怪的属性,这些属性可能会导致这种效果,但是没有运气...

Unless you unchecked the "use AutoLayout" checkbox in your nib/storyboard, you are using AutoLayout, so the system adds constraints to your views if you don't. 除非您在笔尖/故事板上未选中“使用自动布局”复选框,否则您将使用自动布局,因此,如果不使用,则系统会向视图添加约束。

When using AutoLayout you can't modify the frame/bounds/center of a view directly, or exactly what you describe happens. 使用自动版式时,您无法直接修改视图的框架/边界/中心,也不能完全修改您描述的内容。 The next time something triggers a layout update, the view snaps back to the position defined by it's constraints. 下次触发布局更新时,视图将恢复到其约束定义的位置。

You either need to turn off AutoLayout for the entire nib/storyboard, or add outlets to your constraints and change the constant value of the contstraint(s), then call layoutIfNeeded() on the view to make the constraint changes take effect. 您要么需要为整个笔尖/故事板关闭AutoLayout,要么将出口添加到约束中并更改约束的常量值,然后在视图上调用layoutIfNeeded()来使约束更改生效。

I suggest adding outlets to the constraints. 我建议在限制条件上增加出口。 Switching to the older style struts-and-springs style form design is a big change, and one that will have large side-effects for your view controller. 切换到较旧的struts-springs样式表单设计是一个很大的变化,并且这将对您的视图控制器产生很大的副作用。 (Personally I prefer struts-and-springs style form design, but I force myself to use AutoLayout because that's the new way of doing things.) (我个人更喜欢使用 struts-and-springs样式的表单设计,但是我强迫自己使用AutoLayout,因为这是新的处理方式。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM