iOS Swift - 带滑块的移动图像
iOS Swift - moving image with slider
我在使用滑块移动 UIImageView 时遇到一些问题。这是我目前使用的代码:
@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)
实际上,我可以使用此代码移动图像,但是:图像总是 "jumps" 回到屏幕中间的原始位置,根本不移动滑块...你知道吗有什么想法,这怎么会发生?我已经在右边的检查器中检查了一些可能导致这种效果的奇怪属性,但运气不好...
除非您取消选中 nib/storyboard 中的 "use AutoLayout" 复选框,否则您使用的是 AutoLayout,因此如果您不这样做,系统会向您的视图添加约束。
使用 AutoLayout 时,您不能直接修改视图的 frame/bounds/center,否则会发生您描述的情况。下一次触发布局更新时,视图会快速返回到其约束定义的位置。
您需要为整个 nib/storyboard 关闭 AutoLayout,或者将出口添加到您的约束并更改约束的常量值,然后在视图上调用 layoutIfNeeded()
以使约束更改生效。
我建议在约束中添加出口。切换到旧样式 struts-and-springs 样式表单设计是一个很大的变化,并且会对您的视图控制器产生很大的副作用。 (我个人 更喜欢 struts-and-springs 样式的表单设计,但我强迫自己使用 AutoLayout,因为这是新的做事方式。)
我在使用滑块移动 UIImageView 时遇到一些问题。这是我目前使用的代码:
@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)
实际上,我可以使用此代码移动图像,但是:图像总是 "jumps" 回到屏幕中间的原始位置,根本不移动滑块...你知道吗有什么想法,这怎么会发生?我已经在右边的检查器中检查了一些可能导致这种效果的奇怪属性,但运气不好...
除非您取消选中 nib/storyboard 中的 "use AutoLayout" 复选框,否则您使用的是 AutoLayout,因此如果您不这样做,系统会向您的视图添加约束。
使用 AutoLayout 时,您不能直接修改视图的 frame/bounds/center,否则会发生您描述的情况。下一次触发布局更新时,视图会快速返回到其约束定义的位置。
您需要为整个 nib/storyboard 关闭 AutoLayout,或者将出口添加到您的约束并更改约束的常量值,然后在视图上调用 layoutIfNeeded()
以使约束更改生效。
我建议在约束中添加出口。切换到旧样式 struts-and-springs 样式表单设计是一个很大的变化,并且会对您的视图控制器产生很大的副作用。 (我个人 更喜欢 struts-and-springs 样式的表单设计,但我强迫自己使用 AutoLayout,因为这是新的做事方式。)