我正在创建一个简单的应用程序,允许用户每天写一两句话。
我有一个UICollectionView将每个日子显示为一个单元格。在该单元格中,有一个UITextView,用户可以在其中输入文本。他们输入的文本保存在Core Data中。
每个单元格使用用户输入的文本(从Core Data获取)填充UITextView。但是如果用户当天没有输入文本,那么UITextView会填充一个NSAttributedString,其中包含一个图像和一个字符串,以鼓励用户输入文本。
问题是具有NSAttributedString的单元格导致CollectionView滚动非常滞后且不连贯。
导致延迟的具体因素是NSAttributedString中的图像。图像来自xcassets。
那么如何在多个单元格上使用相同的图像(在NSAttributedString中)并且没有延迟滚动?
override func viewWillAppear(_ animated: Bool) {
collectionView.delegate = self
super.viewWillAppear(animated)
collectionView.setNeedsLayout()
collectionView.layoutIfNeeded()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dates.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellSize = CGSize(width: round(UIScreen.main.bounds.width * 0.8125), height: 469)
return cellSize
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.fetchedResultsController = fetchedResultsController
cell.date = dates[indexPath.item]
return cell
}
@IBOutlet var textView: UITextView!
var date = Date() {
didSet {
loadTextViewData()
}
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)!
self.setNeedsLayout()
self.layoutIfNeeded()
}
func loadTextViewData(){
let entity = CoreDataMethods.fetchEntity(date: date)
if (entity != nil){
textView.attributedText = NSAttributedString(string:entity?.value(forKey: "textViewEntry") as! String)
} else {
loadPromptText()
}
}
func loadPromptText(){
let style = NSMutableParagraphStyle()
style.lineSpacing = 10
style.alignment = .center
textView.attributedText = NSAttributedString(string: "Tap here to enter!" , attributes: [NSAttributedStringKey.paragraphStyle : style, NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 16.0)!])
let attributedString = NSMutableAttributedString(attributedString:textView.attributedText )
let textAttachment = NSTextAttachment()
textAttachment.image = #imageLiteral(resourceName: "EditIcon")
textAttachment.image = UIImage(cgImage: textAttachment.image!.cgImage!, scale: CGFloat(7.0), orientation: .up)
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.append(attrStringWithImage)
textView.attributedText = attributedString;
}