如何在iOS swift中水平滚动图像

iVJ*_*iVJ 0 image uiscrollview ios swift

我有一个名为“cardImgView”的图像视图,因为我想通过水平滚动来加载两个图像,我尝试了以下方法,在这种情况下,我只能向上和向下滚动,并且图像也不会改变,任何人都知道如何正确地做到这一点。

let img: UIImage = self.dataDict.object(forKey: kCardImgFront) as! UIImage
let img2:UIImage = self.dataDict.object(forKey: kCardImgBack) as! UIImage
imgArray = [img, img2]        

for i in 0..<imgArray.count{           
    cardImgView?.image = imgArray[i]                        
    scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
    scrollView.addSubview(cardImgView!)
}
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Don*_*Mag 5

首先,正如我所评论的,您当前使用的是单个图像UIImageView视图,因此每次通过 for 循环时,您只是替换.image该图像视图的 。

其次,使用自动布局和约束会更好,而不是尝试显式设置框架和滚动视图的内容大小。

第三,UIStackView非常适合您的用例 - 添加您想要水平滚动的多个图像。

所以,总体思路是:

  • 添加滚动视图
  • 将堆栈视图添加到滚动视图
  • 使用约束使堆栈视图控制滚动视图的 contentSize
  • UIImageView为每个图像创建一个新的
  • 将每个图像视图添加到堆栈视图

这是一个简单的示例,您可以在 Playground 页面中运行它以查看其工作原理。如果您将自己的名为 image1.png 和 image2.png 的图像添加到游乐场的资源中,则会使用它们(否则,此示例将创建纯蓝色和纯绿色图像):

import UIKit
import PlaygroundSupport

// UIImage extension to create a new, solid-color image
public extension UIImage {
    public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        let rect = CGRect(origin: .zero, size: size)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        guard let cgImage = image?.cgImage else { return nil }
        self.init(cgImage: cgImage)
    }
}

class TestViewController : UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // create a UIScrollView
        let scrollView = UIScrollView()

        // we will set the auto-layout constraints
        scrollView.translatesAutoresizingMaskIntoConstraints = false

        // set background color so we can see the scrollView when the images are scrolled
        scrollView.backgroundColor = .orange

        // add the scrollView to the view
        view.addSubview(scrollView)

        // pin scrollView 20-pts from top/bottom/leading/trailing
        scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0).isActive = true
        scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20.0).isActive = true
        scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20.0).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20.0).isActive = true

        // create an array of empty images in case this is run without
        // valid images in the resources
        var imgArray = [UIImage(color: .blue), UIImage(color: .green)]

        // if these images exist, load them and replace the blank images in imgArray
        if  let img1: UIImage = UIImage(named: "image1"),
            let img2: UIImage = UIImage(named: "image2") {

            imgArray = [img1, img2]

        }

        // create a UIStackView
        let stackView = UIStackView()

        // we can use the default stackView properties
        // but can change axis, alignment, distribution, spacing, etc if desired

        // we will set the auto-layout constraints
        stackView.translatesAutoresizingMaskIntoConstraints = false

        // add the stackView to the scrollView
        scrollView.addSubview(stackView)

        // with auto-layout, scroll views use the content's constraints to
        // determine the contentSize,
        // so pin the stackView to top/bottom/leading/trailing of the scrollView
        stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 0.0).isActive = true
        stackView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0.0).isActive = true
        stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: 0.0).isActive = true
        stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0.0).isActive = true

        // loop through the images
        for img in imgArray {

            // create a new UIImageView
            let imgView = UIImageView(image: img)

            // we will set the auto-layout constraints, and allow the stackView
            // to handle the placement
            imgView.translatesAutoresizingMaskIntoConstraints = false

            // set image scaling as desired
            imgView.contentMode = .scaleToFill

            // add the image view to the stackView
            stackView.addArrangedSubview(imgView)

            // set imgView's width and height to the scrollView's width and height
            imgView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 1.0).isActive = true
            imgView.heightAnchor.constraint(equalTo: scrollView.heightAnchor, multiplier: 1.0).isActive = true

        }

    }

}

let vc = TestViewController()
vc.view.backgroundColor = .red
PlaygroundPage.current.liveView = vc
Run Code Online (Sandbox Code Playgroud)