2017-10-18 181 views
-1

我已經將UIImageView放在屏幕上的UIScrollView下,屏幕的寬度與屏幕的寬度相同,並且它在iPhone 5s中正常工作,但在iPhone 7或8上,圖像的大小小於寬度屏幕大小在屏幕截圖上共享。UIImageView在UIScrollview不適合頂部屏幕

這裏是我的代碼:

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 8story boardIphone 5s Screenshot

+0

不要用戶滾動視圖寬度,用[UIScreen mainScreen] .bounds.size.width;並在ViewWillAppear或ViewDidAppear中計算幀。 – Kuldeep

+0

請檢查此:https://stackoverflow.com/questions/39021503/custom-view-self-frame-is-not-correct – Amit

+0

我也遇到同樣的問題,並嘗試使用'layoutSubviews','setNeedsLayout'和' layoutIfNeeded'。沒有工作。然後我通過具有水平滾動的'collectionView'去除了滾動視圖。 – Amit

回答

0

短褲,視圖可能沒有更新的viewDidLoad或viewWillAppear中的方法,而不是幀視圖以故事板大小初始化。所以你沒有得到更新的iPhone 7或其他設備。 另一個原因是scrollview會自動調整它的子視圖。所以在viewDidLoad()上禁用它。

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

    // write your code 

    } 

因爲你已經做了和更新框架&滾動視圖內容相關的上viewDidLayoutSubviews改變你應該在viewDidLoad中添加子視圖()()方法。

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) 
} 

希望將工作。

0

您希望框架寬度爲屏幕寬度。使用如:

let size = UIScreen.main.bounds.size 

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