美文网首页iOS Developer
【iOS】xib+10行代码搞定scrollview图片查看

【iOS】xib+10行代码搞定scrollview图片查看

作者: 清無 | 来源:发表于2017-03-31 13:54 被阅读134次
    最终效果
    • Platform: iOS8.0+
    • Language: Swift3.0
    • Editor: Xcode8
    1.在storyboard上拖一个UIScrollView
    scrollview 约束
    2.再在UIScrollView中拖一个UIImageView
    01 imageview 约束 02 为了避免约束报错/警告,给imageview设置一张图片 03 Update Frames
    3.绑定@IBOutlet
        @IBOutlet weak var scrollView: UIScrollView!
        @IBOutlet weak var imageView: UIImageView!
        
    // 约束 - 居中显示用
        @IBOutlet weak var ivLeadingCons: NSLayoutConstraint!
        @IBOutlet weak var ivTrailingCons: NSLayoutConstraint!
        @IBOutlet weak var ivTopCons: NSLayoutConstraint!
        @IBOutlet weak var ivBottomCons: NSLayoutConstraint!
    
    4.添加方法
        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
    
            scaleImageViewForAdjustingViewSize()
        }
        
        // 缩放到屏幕合适
        fileprivate func scaleImageViewForAdjustingViewSize()
        {
            let minScale = min(view.bounds.size.width / imageView.bounds.size.width, view.bounds.size.height / imageView.bounds.size.height)
            
            scrollView.minimumZoomScale = minScale //最小缩放值
            scrollView.zoomScale = minScale //当前缩放值
        }
        
        // 居中显示
        fileprivate func updateConstraintsForPositioningImageViewCenterly()
        {
           let yOffset = max(0, (view.bounds.size.height - imageView.frame.size.height)/2)
            
            let xOffset = max(0, (view.bounds.size.width - imageView.frame.size.width)/2)
            
            // 设置约束 - 相当于设置scrollview的contentsize,这样它才能滚动内容
            ivTopCons.constant = yOffset
            ivBottomCons.constant = yOffset
            ivLeadingCons.constant = xOffset
            ivTrailingCons.constant = xOffset
            
            view.layoutIfNeeded()
        }
    
    extension ViewController: UIScrollViewDelegate{
        func viewForZooming(in scrollView: UIScrollView) -> UIView? {
            return imageView
        }
        
        func scrollViewDidZoom(_ scrollView: UIScrollView) {
            updateConstraintsForPositioningImageViewCenterly()
        }
    }
    
    5.Build and run to see what does it looks like.

    如果对你有帮助,别忘了点个❤️哦。

    相关文章

      网友评论

        本文标题:【iOS】xib+10行代码搞定scrollview图片查看

        本文链接:https://www.haomeiwen.com/subject/rzxvottx.html