gpt4 book ai didi

Swift - 如何在 ScrollView 中应用调整图像大小

转载 作者:行者123 更新时间:2023-11-30 10:11:27 25 4
gpt4 key购买 nike

我有以下 ScrollView 代码

class ViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var pageControl: UIPageControl!

var imageArray = [UIImage(named: "mainScrollView1"), UIImage(named: "mainScrollView2"), UIImage(named: "mainScrollView3"),]

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

configurePageControl()

scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.delegate = self

for var i = 0; i < imageArray.count; i++ {

if i == 0 {

var imageView = UIImageView(frame: CGRectMake(0, 0, scrollView.frame.size.width, 160))
imageView.image = imageArray[i]
scrollView.addSubview(imageView)

} else {

var float: CGFloat = CGFloat(i)
var imageView = UIImageView(frame: CGRectMake(scrollView.frame.size.width * float, 0, scrollView.frame.size.width, 160))
imageView.image = imageArray[i]
scrollView.addSubview(imageView)

}
}

scrollView.contentSize = CGSizeMake(scrollView.frame.size.width*3, scrollView.frame.size.height)

}

func configurePageControl() {

self.pageControl.numberOfPages = 3
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.redColor()
self.pageControl.pageIndicatorTintColor = UIColor.blackColor()
self.pageControl.currentPageIndicatorTintColor = UIColor.whiteColor()
self.view.addSubview(pageControl)

}

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}

}

问题是内部的图像滚动为静态图像,它们不会根据不同的屏幕尺寸更改其大小,因此它看起来像这样

enter image description here

如您所见,第一张图片不会扩展以填充整个屏幕宽度,因此可以看到第二张图片的这一部分

如何解决这个问题?

最佳答案

您应该在 View 布局所有 subview 之后更新图像大小。您应该在 viewDidLayoutSubviews 中执行此操作。

类似这样的事情:

var imageArray = [UIImage(named: "mainScrollView1"), UIImage(named: "mainScrollView2"), UIImage(named: "mainScrollView3"),]
var imageViews:[UIImageView] = []

override func viewDidLoad() {
super.viewDidLoad()
configurePageControl()

scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.delegate = self

for image in imageArray {
var imageView = UIImageView(image: image)
scrollView.addSubview(imageView)
imageViews.append(imageView)
}
}

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()

for (index,imageView) in imageViews.enumerate() {
imageView.frame = CGRectMake(CGFloat(index)*scrollView.frame.size.width, 0, scrollView.frame.size.width, 160)
}
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width*3, scrollView.frame.size.height)
}

关于Swift - 如何在 ScrollView 中应用调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32778549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com