Размер содержимого страницы прокрутки просмотра не работает с iphone 5s ios 12 - PullRequest
0 голосов
/ 02 августа 2020

У меня есть горизонтальная прокрутка страниц с 3 изображениями. Это код в моем viewDidLoad:

for index in 0..<images.count {
    frame.origin.x = scrollView.frame.size.width * CGFloat(index)
    frame.size = scrollView.frame.size
              
    let UrlImage = NSURL(string: images[index] as! String)
    let dataImage = NSData(contentsOf: UrlImage! as URL)
    if dataImage != nil {
                                
        let imgView = UIImageView(frame: frame)
        imgView.image = UIImage(data: dataImage! as Data)
        imgView.contentMode = .scaleAspectFit
        self.scrollView.backgroundColor = .lightGray
        self.scrollView.addSubview(imgView)
                                
    }
}

scrollView.contentSize = CGSize(width: (scrollView.frame.size.width * CGFloat(images.count)), height: scrollView.frame.size.height)
scrollView.delegate = self

, и вот результат: enter image description here

If i try with last iphone devices it works properly. But if i try with iphone 5s with ios12, content size doesn't work and this is the result:

введите описание изображения здесь

Как это исправить? 3 дня пытаюсь

1 Ответ

0 голосов
/ 03 августа 2020

Я предполагаю, что у вас есть код для обработки элемента управления страницей и делегатов прокрутки ...

Вот очень простой пример использования UIStackView для хранения трех представлений изображений:

class ViewController: UIViewController {

    let scrollView = UIScrollView()
    let stack = UIStackView()
    let pageControl = UIPageControl()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // scroll view properties
        scrollView.backgroundColor = .gray
        scrollView.isPagingEnabled = true
        
        // stack view properties
        stack.axis = .horizontal
        stack.alignment = .fill
        stack.distribution = .fillEqually
        stack.spacing = 0

        // page control properties
        pageControl.backgroundColor = .white
        pageControl.pageIndicatorTintColor = .darkGray
        pageControl.currentPageIndicatorTintColor = .blue
        
        // we're going to use constraints
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        stack.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false

        scrollView.addSubview(stack)
        view.addSubview(scrollView)
        view.addSubview(pageControl)
        
        // respect safe area
        let g = view.layoutMarginsGuide
        
        NSLayoutConstraint.activate([

            // scroll view constrained Top / Leading / Trailing
            scrollView.topAnchor.constraint(equalTo: g.topAnchor),
            scrollView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
            
            // scroll view height = 1/2 of view height
            scrollView.heightAnchor.constraint(equalTo: g.heightAnchor, multiplier: 0.5),
            
            // stack view constrained Top / Bottom / Leading / Trailing of scroll view
            stack.topAnchor.constraint(equalTo: scrollView.topAnchor),
            stack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            stack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            stack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            
            // stack view height == scroll view height
            stack.heightAnchor.constraint(equalTo: scrollView.heightAnchor),
            
            // page control centered horizontally just below the scroll view
            pageControl.topAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 4.0),
            pageControl.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
            
        ])
        
        // add three image views to the stack view
        for _ in 1...3 {
            let v = UIImageView()
            v.backgroundColor = .lightGray
            v.contentMode = .scaleAspectFit
            stack.addArrangedSubview(v)
        }
        
        // stack distribution is set to .fillEqually, so we only need to set the
        // width constraint on the first image view
        
        // unwrap it
        if let v = stack.arrangedSubviews.first {
            // stack view has 8-pts on each side
            v.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
        }
        
        pageControl.numberOfPages = 3
        
        // set delegates...
        // implement page control funcs...
        // etc...
        
        // start image retrieval process
        downloadImages()
    }

    func downloadImages() -> Void {
        // get 3 "placeholder" images
        // 400x300  400x400  300x400
        
        let urls: [String] = [
            "https://via.placeholder.com/400x300.png/FF0000/FFF",
            "https://via.placeholder.com/400x400.png/00AA00/FFF",
            "https://via.placeholder.com/300x400.png/0000FF/FFF",
        ]
        
        for (v, urlString) in zip(stack.arrangedSubviews, urls) {
            if let imgView = v as? UIImageView, let url = URL(string: urlString)  {
                imgView.load(url: url)
            }
        }
    }

}

// async download image url from: https://www.hackingwithswift.com/example-code/uikit/how-to-load-a-remote-image-url-into-uiimageview
extension UIImageView {
    func load(url: URL) {
        DispatchQueue.global().async { [weak self] in
            if let data = try? Data(contentsOf: url) {
                if let image = UIImage(data: data) {
                    DispatchQueue.main.async {
                        self?.image = image
                    }
                }
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...