我正在使用此扩展程序将文本垂直居中于文本视图中。
extension UITextView {
func centerVertically() {
let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
let size = sizeThatFits(fittingSize)
let topOffset = (bounds.size.height - size.height * zoomScale) / 2
let positiveTopOffset = max(1, topOffset)
contentOffset.y = -positiveTopOffset
}
}
但由于某种原因,它在视图加载时不会影响textview。但是当我将集合视图单元格滚动3次时,它可以正常工作。我在这一行调用扩展名。 cell.textView.centerVertically()
有什么想法吗?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
let randomJoke = Int(arc4random()) % jokes.count
cell.textView.text = jokes[randomJoke]
if UIScreen.main.bounds.height == 736 {
cell.stackViewTop.constant = 40
cell.stackViewBottom.constant = 100
}
cell.textView.centerVertically()
return cell
}