UIScrollview下的UIImageView不适合顶部屏幕

时间:2017-10-18 06:35:31

标签: ios iphone swift uiscrollview uiimageview

我在UIScrollView下放置UIImageView,屏幕宽度恒定,与iphone 5s一样正常,但在iphone 7或8上,图片大小小于屏幕截图上共享的屏幕尺寸宽度。

这是我的代码:

    let x = CGFloat(selectedEvent.album?.count ?? 0)

    pageControl.numberOfPages = (selectedEvent.album?.count ?? 0)

    for index in 0..<(selectedEvent.album?.count ?? 0) {

        frame.origin.x = scroll.frame.size.width * CGFloat(index)
        frame.size = scroll.frame.size

        print(self.frame.size.width)
        print(scroll.frame.size.width)
        print(frame.size.width)

        let image = UIImageView(frame: frame)
        image.contentMode = .scaleToFill

        print(image.frame.size.width)

        if (selectedEvent.album?.count ?? 0) > 0 {
            selectedEvent.getAlbumImage(key: selectedEvent.album![index], completion: { (gotImage:UIImage) in
                image.image = gotImage
            })
        } else {
            image.image = UIImage(named: "defaultImage.jpg")
        }

        scroll .addSubview(image)
    }

    self.scroll.contentSize = CGSize(width: scroll.frame.size.width * x, height: scroll.frame.size.height)
    pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)

这是打印日志

320.0
320.0
320.0
320.0
320.0
320.0
320.0
320.0

Iphone 8 story board Iphone 5s Screenshot

2 个答案:

答案 0 :(得分:0)

简而言之,视图可能没有在viewDidLoad或ViewWillAppear方法上更新帧,而是使用storyboard大小初始化视图。所以你没有得到iPhone 7或其他设备的更新rect。 另一个原因是scrollview会自动调整它的子视图。所以在viewDidLoad()上禁用它。

override func viewDidLoad() {
    super.viewDidLoad()
    self.scroll.contentInsetAdjustmentBehavior = .never;

    // write your code

  }

您应该像已经完成的那样在viewDidLoad()方法上添加子视图并更新框架&amp; scrollD内容与viewDidLayoutSubviews()相关的更改。

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews();
    for view:UIView in self.scroll.subviews {
        frame.origin.x = self.scroll.frame.size.width * CGFloat(self.scroll.subviews.index(of: view)!);
        frame.size = scroll.frame.size
        view.frame = frame;
    }

    self.scroll.contentSize = CGSize(width: scroll.frame.size.width * selectedEvent.album?.count , height: scroll.frame.size.height)
}

希望会奏效。

答案 1 :(得分:0)

您希望框架宽度为屏幕宽度。用作:

let size = UIScreen.main.bounds.size

self.scroll.contentSize = CGSize(width: size.width, height: scroll.frame.size.height)