The UICollectionView Cell photo
下面的UICollectionView Controller代码
import UIKit
import Parse
class homeVC: UICollectionViewController {
// refresher variable
var refresher : UIRefreshControl!
// size of page
//var page : Int = 5
// arrays to hold server information
var uuidArray = [String]()
var contentArray = [String]()
var titleArray = [String]()
// default function
override func viewDidLoad() {
super.viewDidLoad()
// always vertical scroll
self.collectionView?.alwaysBounceVertical = true
// background color
collectionView?.backgroundColor = .white
// title at the top
self.navigationItem.title = PFUser.current()?.username?.uppercased()
// pull to refresh
refresher = UIRefreshControl()
refresher.addTarget(self, action: #selector(homeVC.refresh), for: UIControlEvents.valueChanged)
collectionView?.addSubview(refresher)
// load posts func
loadPosts()
}
// refreshing func
func refresh() {
// reload posts
loadPosts()
// stop refresher animating
refresher.endRefreshing()
}
// load posts func
func loadPosts() {
// request infomration from server
let query = PFQuery(className: "posts")
query.whereKey("username", equalTo: PFUser.current()!.username!)
// query.limit = page
query.findObjectsInBackground (block: { (objects, error) -> Void in
if error == nil {
// clean up
self.uuidArray.removeAll(keepingCapacity: false)
self.contentArray.removeAll(keepingCapacity: false)
self.titleArray.removeAll(keepingCapacity: false)
// find objects related to our request
for object in objects! {
// add found data to arrays (holders)
self.uuidArray.append(object.object(forKey: "uuid") as! String)
self.contentArray.append(object.object(forKey: "content") as! String)
self.titleArray.append(object.object(forKey: "title") as! String)
}
self.collectionView?.reloadData()
} else {
print(error!.localizedDescription)
}
})
}
// cell numb
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return contentArray.count
}
// cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let size = CGSize(width: self.view.frame.size.width / 1, height: self.view.frame.size.width / 1)
return size
}
// cell config
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// define cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
// get content and tile from the contentArrary and titleArray to the text Label in cells
cell.contentTxt.text = contentArray[indexPath.row]
cell.titleTxt.text = titleArray[indexPath.row]
return cell
}
// header config
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// define header
let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! headerVC
//Implement tap gestures
// tap followings
let bookedTap = UITapGestureRecognizer(target: self, action: #selector(homeVC.bookedTap))
bookedTap.numberOfTapsRequired = 1
header.booked.isUserInteractionEnabled = true
header.booked.addGestureRecognizer(bookedTap)
// get users data with connections to columns of PFuser class
header.fullnameTxt.text = (PFUser.current()?.object(forKey: "username") as? String)?.uppercased()
let avaQuery = PFUser.current()?.object(forKey: "ava") as! PFFile
avaQuery.getDataInBackground { (data, error) -> Void in
header.avaImg.image = UIImage(data: data!)
}
header.button.setTitle("edit profile", for: UIControlState())
return header
}
// tapped followings label
func bookedTap() {
user = PFUser.current()!.username!
category = "booked"
// make reference to followersVC
let followings = self.storyboard?.instantiateViewController(withIdentifier: "bookedVC") as! bookedVC
// present
self.navigationController?.pushViewController(followings, animated: true)
}
有UICollectionView Cell的代码
import UIKit
class Cell: UICollectionViewCell {
@IBOutlet weak var titleTxt: UILabel!
@IBOutlet weak var contentTxt: UITextView!
}
有headerVC的代码
import UIKit
import Parse
class headerVC: UICollectionReusableView {
@IBOutlet weak var avaImg: UIImageView!
@IBOutlet weak var fullnameTxt: UILabel!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var booked: UIButton!
// default func
override func awakeFromNib() {
super.awakeFromNib()
}
// clicked follow button from GuestVC
@IBAction func followBtn_clicked(_ sender: AnyObject) {
let title = button.title(for: UIControlState())
// to follow
if title == "FOLLOW" {
let object = PFObject(className: "follow")
object["follower"] = PFUser.current()?.username
object["following"] = guestname.last!
object.saveInBackground(block: { (success, error) -> Void in
if success {
self.button.setTitle("FOLLOWING", for: UIControlState())
self.button.backgroundColor = .green
// send follow notification
let newsObj = PFObject(className: "news")
newsObj["by"] = PFUser.current()?.username
newsObj["ava"] = PFUser.current()?.object(forKey: "ava") as! PFFile
newsObj["to"] = guestname.last
newsObj["owner"] = ""
newsObj["uuid"] = ""
newsObj["type"] = "follow"
newsObj["checked"] = "no"
newsObj.saveEventually()
} else {
print(error?.localizedDescription ?? String())
}
})
// unfollow
} else {
let query = PFQuery(className: "follow")
query.whereKey("follower", equalTo: PFUser.current()!.username!)
query.whereKey("following", equalTo: guestname.last!)
query.findObjectsInBackground(block: { (objects, error) -> Void in
if error == nil {
for object in objects! {
object.deleteInBackground(block: { (success, error) -> Void in
if success {
self.button.setTitle("FOLLOW", for: UIControlState())
self.button.backgroundColor = .lightGray
// delete follow notification
let newsQuery = PFQuery(className: "news")
newsQuery.whereKey("by", equalTo: PFUser.current()!.username!)
newsQuery.whereKey("to", equalTo: guestname.last!)
newsQuery.whereKey("type", equalTo: "follow")
newsQuery.findObjectsInBackground(block: { (objects, error) -> Void in
if error == nil {
for object in objects! {
object.deleteEventually()
}
}
})
} else {
print(error?.localizedDescription ?? String())
}
})
}
} else {
print(error?.localizedDescription ?? String())
}
})
}
}
CollectionView Cell中有很多空格,如何根据SWIFT3中单词的长度自动更改单元格的高度?
我尝试了很多方法,但这些方法适用于tableview。
答案 0 :(得分:0)
首先,您需要在UICollectionViewFlowLayout上设置estimatedItemSize。这样,当您设置estimatedItemSize
属性时,Flow布局将变为动态。
self.flowLayout.estimatedItemSize = CGSize(width: 100, height: 100)
然后在自定义单元格类中实现preferredLayoutAttributesFittingAttributes
var heightCalculated: Bool = false
override func preferredLayoutAttributesFittingAttributes(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
//store height to avoid indefinite calling.
if !heightCalculated {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFittingSize(layoutAttributes.size)
var newFrame = layoutAttributes.frame
newFrame.size.width = CGFloat(ceilf(Float(size.width)))
layoutAttributes.frame = newFrame
heightCalculated = true
}
return layoutAttributes
}
这是指向教程的链接,非常清楚地详细解释https://possiblemobile.com/2016/02/sizing-uicollectionviewcell-fit-multiline-uilabel/