我的故事板中定义了UIScrollView,带有插座。此scrollview通过代码(不在故事板上)添加了一个UIImageView。当我运行应用程序时,图像被拉伸出方面。只要我触摸缩放图像,它就会捕捉到适当的宽高比。
这是怎么回事?!
@IBOutlet var scrollView: UIScrollView!
var imageView = UIImageView()
var selectedImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
imageView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height)
imageView.image = selectedImage
imageView.contentMode = .ScaleAspectFit
imageView.userInteractionEnabled = true
scrollView.contentMode = .ScaleAspectFit
scrollView.addSubview(imageView)
let scrollViewFrame = scrollView.frame
let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
let minScale = min(scaleHeight, scaleWidth)
scrollView.minimumZoomScale = 0.3
scrollView.maximumZoomScale = 1
scrollView.zoomScale = minScale
centerScrollViewContents()
self.closeBtn.layer.cornerRadius = CGRectGetWidth(self.closeBtn.frame)/20.0
}
ALMOST FIXED: 我编辑了代码来定义viewWillLayoutSubviews中的imageView.frame而不是viewDidLoad,如下面的答案所示。我现在有一个新问题 - 图像无法放大...它允许您缩放,直到您松开手指然后它快速恢复到原始大小。
这与scrollView.maximumZoomScale相比还不够大吗?
更正后的代码:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
imageView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height)
}
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
//imageView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height)
imageView.image = selectedImage
imageView.contentMode = .ScaleAspectFit
imageView.userInteractionEnabled = true
scrollView.contentMode = .ScaleAspectFit
scrollView.addSubview(imageView)
let scrollViewFrame = scrollView.frame
let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
let minScale = min(scaleHeight, scaleWidth)
scrollView.minimumZoomScale = 0.3
scrollView.maximumZoomScale = 2.0
scrollView.zoomScale = minScale
centerScrollViewContents()
self.closeBtn.layer.cornerRadius = CGRectGetWidth(self.closeBtn.frame)/20.0
}
答案 0 :(得分:1)
在-viewDidLoad()方法中设置框架还为时过早
如果你将在-viewDidLoad()中打印你的scrollView.frame,这将实际返回框架,然后你的视图将布局它的子视图。
所以你需要在viewWillLayout中对imageView进行约束或重新定义imageView.frame。