2013-03-23 10 views
18

Questo dovrebbe essere un problema MOLTO facile, ma ho problemi a ottenere il risultato desiderato. Ho orizzontale scrolling UIScrollView con una larghezza di 320. La larghezza del suo contenuto è 5000. Sto cercando di centrare il contenuto con:Come centrare il contenuto in un UIScrollView con contentOffset

// 'self' is the UIScrollView 
CGFloat newContentOffsetX = (self.width/2) + (self.contentSize.width/2); 
self.contentOffset = CGPointMake(newContentOffsetX, 0); 

Non capisco perché questo non è centraggio dei contenuti. Riesci a vedere qualcosa di sbagliato con i calcoli?

risposta

52

Penso che si desidera:

CGFloat newContentOffsetX = (self.contentSize.width/2) - (self.bounds.size.width/2); 

schema:

|------------------------self.contentSize.width------------------------| 
         |-----self.width-----| 
|-------- offset --------| 
            ^center 
+1

Mi spiace per la confusione "auto.width". Questa è una scorciatoia che ho aggiunto con una categoria UIView. Perché stai usando self.bounds invece di self.frame? – zakdances

+1

Sospettavo che 'self.width' non fosse il problema, in realtà, è che vuoi sottrarre quello da' contentSize.width', ma ho usato 'self.bounds 'per abitudine. 'self.bounds.size' e' self.frame.size' dovrebbero essere uguali; Tendo ad usare 'self.bounds' a meno che non abbia bisogno dell'origine-relativo-a-superview che ottengo con' self.frame.origin'. – Isaac

11

Uso sottostante Codice:

CGFloat newContentOffsetX = (scrollView.contentSize.width - scrollView.frame.size.width)/2; 
scrollView.contentOffset = CGPointMake(newContentOffsetX, 0); 
0

Swift 4

Scorrere fino a c inserire il contenuto di ScrollView

let centerOffsetX = (scrollView.contentSize.width - scrollView.frame.size.width)/2 
let centerOffsetY = (scrollView.contentSize.height - scrollView.frame.size.height)/2 
let centerPoint = CGPoint(x: centerOffsetX, y: centerOffsetY) 
scrollView.setContentOffset(centerPoint, animated: true) 
Problemi correlati