Oblique table view cells in iOS - ios

How can I implement this? A table view with oblique cells. I was thinking first to make the cells overlap and cut out a piece, but I can't make it work.
Now the single solution I can think of is to download the second image in first cell and cut out the top triangle and add to the first cell. But that wouldn't be too optimal memory wise and processing wise if the user is scrolling through the list.
I appreciate any advice, thank you!

I've done something similar like this but I didn't use UITableView or UICollectionView.
What I use is having one UIImageView(AView) on top of the other UIImageView(BView) in view hieararchy. So I add UISwipeGestureRecognizer to BView .And at the top of BView I've added a seperator view(when VC load user could not see it). And I basically animating BView however I want.
But since they are not cells in UITableView you can't give "pulling" behavior to user which is a UX disadvantage for your app.

I solved it the following way. I used UICollectionView in the end because I couldn't find a way to overlap nicely the cells from UITableView. So first I made a custom layout which looks like this:
CustomCollectionViewFlowLayout.swift
import UIKit
class CustomCollectionViewFlowLayout: UICollectionViewFlowLayout {
override func collectionViewContentSize() -> CGSize {
let xSize = self.itemSize.width
let ySize = CGFloat(self.collectionView!.numberOfItemsInSection(0)) * self.itemSize.height
var size = CGSizeMake(xSize, ySize)
if self.collectionView!.bounds.size.width > size.width {
size.width = self.collectionView!.bounds.size.width
}
if self.collectionView!.bounds.size.height > size.height {
size.height = self.collectionView!.bounds.size.height
}
return size
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
let attributesArray = super.layoutAttributesForElementsInRect(rect) as! [UICollectionViewLayoutAttributes]
let numberOfItems = self.collectionView?.numberOfItemsInSection(0)
for attribute in attributesArray {
let xPosition = attribute.center.x
var yPosition = attribute.center.y
if attribute.indexPath.row == 0 {
attribute.zIndex = Int(INT_MAX)
} else {
yPosition -= CGFloat(60 * attribute.indexPath.row)
attribute.zIndex = numberOfItems! - attribute.indexPath.row
}
attribute.center = CGPointMake(xPosition, yPosition)
}
return attributesArray
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
return UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
}
}
Then I used paths and shapes to cut out that part and also draw a white rectangle. So it looks like this:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ChallengeCollectionViewCell", forIndexPath: indexPath) as! ChallengeCollectionViewCell
cell.challengeImage.sd_setImageWithURL(NSURL(string: STATIC_IMAGE_URL), completed: nil)
let trianglePath = CGPathCreateMutable()
CGPathMoveToPoint(trianglePath, nil, 0, 0)
CGPathAddLineToPoint(trianglePath, nil, 0, cell.challengeImage!.frame.size.height)
CGPathAddLineToPoint(trianglePath, nil, cell.challengeImage!.frame.size.width, cell.challengeImage!.frame.size.height - 50)
CGPathAddLineToPoint(trianglePath, nil, cell.challengeImage!.frame.width, 0)
CGPathAddLineToPoint(trianglePath, nil, 0, 0)
CGPathCloseSubpath(trianglePath)
let shapeLayer = CAShapeLayer()
shapeLayer.frame = cell.challengeImage!.frame
shapeLayer.path = trianglePath
cell.challengeImage.layer.mask = shapeLayer
cell.challengeImage.layer.masksToBounds = true
let linePath = CGPathCreateMutable()
CGPathMoveToPoint(linePath, nil, 0, cell.challengeImage!.frame.size.height)
CGPathAddLineToPoint(linePath, nil, cell.challengeImage!.frame.size.width, cell.challengeImage!.frame.size.height - 50)
CGPathCloseSubpath(linePath)
let lineShape = CAShapeLayer()
lineShape.path = linePath
lineShape.lineWidth = 10
lineShape.strokeColor = UIColor.whiteColor().CGColor
cell.challengeImage.layer.addSublayer(lineShape)
return cell
}
I hope it will be useful for someone who runs into the same problem. Thanks and best wishes!

Related

Autoresize UICollectionView cells, Align cell to top

I've a UICollectionView, with multiple sections and rows.
Header and Footer views wherever necessary, of fixed size.
Cells that are autoresizable
The cell view are designed like :
Green colour - ImageView
Orange colour - Labels with numberOfLines = 0.
The cell should expand it's size according to label numberOfLines.
I've achieved this using this code in MyCustomCell :
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
super.apply(layoutAttributes)
let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
let targetSize = CGSize(width: Constants.screenWidth/3.5, height: 0)
let autoLayoutSize = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.defaultLow)
let autoLayoutFrame = CGRect(origin: autoLayoutAttributes.frame.origin, size: autoLayoutSize)
autoLayoutAttributes.frame = autoLayoutFrame
return autoLayoutAttributes
}
The cells are autoresizing but the contentView (in cyan colour) are Centre aligned both vertically and horizontally.
I need to make it vertically align to Top.
I had the alignment problem with headers and footers too. For that i've subclassed UICollectionViewFlowLayout
class MainCollectionViewFlowLayout: UICollectionViewFlowLayout {
override func invalidationContext(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutInvalidationContext {
let context: UICollectionViewLayoutInvalidationContext = super.invalidationContext(forPreferredLayoutAttributes: preferredAttributes, withOriginalAttributes: originalAttributes)
let indexPath = preferredAttributes.indexPath
context.invalidateSupplementaryElements(ofKind: UICollectionView.elementKindSectionFooter, at: [indexPath])
context.invalidateSupplementaryElements(ofKind: UICollectionView.elementKindSectionHeader, at: [indexPath])
return context
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)
var topMargin = sectionInset.top
var leftMargin = sectionInset.left
var maxY: CGFloat = -1.0
attributes?.forEach { layoutAttribute in
guard layoutAttribute.representedElementCategory == .cell else {
return
}
if layoutAttribute.frame.origin.y >= maxY {
leftMargin = sectionInset.left
topMargin = sectionInset.top
}
layoutAttribute.frame.origin.x = leftMargin
leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
maxY = max(layoutAttribute.frame.maxY , maxY)
}
return attributes
}
}
Here is an image to illustrate current situation. The cyan are contentView of cells. I've to make it align to Top.
EDIT:
So i realised that UICollectionViewFlowLayout code was creating more bugs than fixing a problem. I added layoutAttributesForElements to left align my cell in case there is only one cell. What it actually did was align all of my cells to the left.
Modified the code as
class MainCollectionViewFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)
if attributes?.count == 1 {
if let currentAttribute = attributes?.first {
currentAttribute.frame = CGRect(x: self.sectionInset.left, y: currentAttribute.frame.origin.y, width: currentAttribute.frame.size.width, height: currentAttribute.frame.size.height)
}
}
return attributes
}
}
Now my UICollectionViewCell are properly aligned to horizontal centre with exception to if only one cell which will be left aligned.
Still no solution for vertical alignment.
So I worked around this for quite a bit. No answers from stack overflow help in any way. So i played with custom UICollectionViewFlowLayout method layoutAttributesForElements.
This method will call for every section, and will have layoutAttributesForElements for rect. This will give an array of UICollectionViewLayoutAttributes which one can modify as per the need.
I was having problem figuring out the y coordinate which I would like to change for my cells.
So first with a loop in attributes from layoutAttributesForElements I got the header and saved it's height in a variable. Then changed the rest of cell's y coordinate with the headerHeight value.
Not sure if this is the right way or not, nor did any performance testing. For now everything seems fine without any lag or jerk.
Here is full code or custom UICollectionViewFlowLayout.
class MainCollectionViewFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attr = super.layoutAttributesForElements(in: rect)
var attributes = [UICollectionViewLayoutAttributes]()
for itemAttributes in attr! {
let itemAttributesCopy = itemAttributes.copy() as! UICollectionViewLayoutAttributes
// manipulate itemAttributesCopy
attributes.append(itemAttributesCopy)
}
if attributes.count == 1 {
if let currentAttribute = attributes.first {
currentAttribute.frame = CGRect(x: self.sectionInset.left, y: currentAttribute.frame.origin.y, width: currentAttribute.frame.size.width, height: currentAttribute.frame.size.height)
}
} else {
var sectionHeight: CGFloat = 0
attributes.forEach { layoutAttribute in
guard layoutAttribute.representedElementCategory == .supplementaryView else {
return
}
if layoutAttribute.representedElementKind == UICollectionView.elementKindSectionHeader {
sectionHeight = layoutAttribute.frame.size.height
}
}
attributes.forEach { layoutAttribute in
guard layoutAttribute.representedElementCategory == .cell else {
return
}
if layoutAttribute.frame.origin.x == 0 {
sectionHeight = max(layoutAttribute.frame.minY, sectionHeight)
}
layoutAttribute.frame = CGRect(origin: CGPoint(x: layoutAttribute.frame.origin.x, y: sectionHeight), size: layoutAttribute.frame.size)
}
}
return attributes
}
}
NOTE: You need to copy the attributes in an array first to work with. Else xcode will yell Logging only once for UICollectionViewFlowLayout cache mismatched frame in console.
If any new/perfect solution is there please let me know.
CHEERS!!!

How to place UIView on top of other UIView?

Right now I have a collectionView for which each cell contains a horizontal stackView. The stackView gets populated with a series of UIViews (rectangles), one for each day of a month - each cell corresponds to a month. I fill the stack views like so:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.collectionView {
...
return cell
} else if collectionView == self.timeline {
let index = indexPath.row
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM"
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: timelineMonthCellReuseIdentifier, for: indexPath) as! SNTimelineMonthViewCell
let firstPost = posts.first?.timeStamp
let month = Calendar.current.date(byAdding: .month, value: index, to: firstPost!)
print(dateFormatter.string(from: month!),dateFormatter.string(from: firstPost!),"month diff")
for post in posts {
print(post.timeStamp, "month diff")
}
cell.monthLabel.text = dateFormatter.string(from: month!)
cell.monthLabel.textAlignment = .center
if let start = month?.startOfMonth(), let end = month?.endOfMonth(), let stackView = cell.dayTicks {
var date = start
while date <= end {
let line = UIView()
if posts.contains(where: { Calendar.current.isDate(date, inSameDayAs: $0.timeStamp) }) {
line.backgroundColor = UIColor(red:0.15, green:0.67, blue:0.93, alpha:1.0)
let tapGuesture = UITapGestureRecognizer(target: self, action: #selector (self.tapBar (_:)))
line.isUserInteractionEnabled = true
line.addGestureRecognizer(tapGuesture)
self.dayTicks[date] = line
} else {
line.backgroundColor = UIColor.clear
}
stackView.addArrangedSubview(line)
date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
}
}
return cell
} else {
preconditionFailure("Unknown collection view!")
}
}
Then, when the user stops scrolling a different collection view, I want to add a subview called arrowView ontop of the dayTick (see how self.dayTicks gets populated with the subviews of the stackView above).
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentIndex = self.collectionView.contentOffset.x / self.collectionView.frame.size.width
let post = posts[Int(currentIndex)]
for (_,tick) in self.dayTicks {
tick.subviews.forEach({ $0.removeFromSuperview() })
}
let day = Calendar.current.startOfDay(for: post.timeStamp)
let tick = self.dayTicks[day]
let arrow = UIImage(named:"Tracer Pin")
let arrowView = UIImageView(image: arrow)
// arrowView.clipsToBounds = false
print((tick?.frame.origin)!,"tick origin")
// arrowView.frame.origin = (tick?.frame.origin)!
// arrowView.frame.size.width = 100
// arrowView.frame.size.height = 100
tick?.addSubview(arrowView)
}
This kind of works and it looks like this:
The red rectangle is added but it appears to the right of the dayTick, and it appears as a long thin rectangle. In actuality, the Tracer Pin image referenced looks like this:
Thats at least where the red color comes from but as you can see its stretching it weird and clipping everything thats not in a rectangular UIView space.
Now note that I commented out the 4 lines that set the size and origin of the arrowView as well as setting clipToBounds to false. When I uncomment these lines - the arrowView simply doesn't show up at all so I must be doing this wrong. What I want is to show something like this:
How can I put it directly on top like that?
Another perspective might be to do this with CALayer. Here are some clues (cut from another project) to help you discover a solution:
#IBInspectable open var slideIndicatorThickness: CGFloat = 5.0 {
didSet {
if slideIndicator != nil { slideIndicator.removeFromSuperlayer() }
let slideLayer = CALayer()
let theOrigin = CGPoint(x: bounds.origin.x, y: bounds.origin.y)
let theSize = CGSize(width: CGFloat(3.0), height: CGFloat(10.0)
slideLayer.frame = CGRect(origin: theOrigin, size: theSize)
slideLayer.backgroundColor = UIColor.orange.cgColor
slideIndicator = slideLayer
layer.addSublayer(slideIndicator)
}
}
fileprivate var slideIndicator: CALayer!
fileprivate func updateIndicator() {
// ..
// Somehow figure out new frame, based on stack view's frame.
slideIndicator.frame.origin.x = newOrigin
}
You may have to implement this on a subclass of UIStackView, or your own custom view that is a wrapper around UIStackView.
It looks like you have a fixed height on the arrowView. Could it be that the red triangle portion is under another view?
Debug View Hierarchy
Click the debug view hierarchy which is the second from right icon - it looks like 3 rectangles. Check to see if the whole image is there.
I ended up using CALayer - thanks to #ouni's suggestion For some reason the CALayer seemed to draw directly on top of the view whereas a subview didn't. One key was unchecking the "Clip to bounds box on the collectionView cell itself (as opposed to the subview) - so that I could draw the flared base of the arrow outside of the collection view cell:
My code looks like this:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == self.collectionView {
print("is collection view")
print(scrollView,"collection view")
let currentIndex = self.collectionView.contentOffset.x / self.collectionView.frame.size.width
let post = posts[Int(currentIndex)]
for (_,tick) in self.dayTicks {
tick.layer.sublayers = nil
}
let day = Calendar.current.startOfDay(for: post.timeStamp)
let tick = self.dayTicks[day]
let arrowLayer = CAShapeLayer()
let path = UIBezierPath()
let start_x = (tick?.bounds.origin.x)!
let start_y = (tick?.bounds.minY)!
let top_width = (tick?.bounds.width)!
let tick_height = (tick?.bounds.height)!
let tip_height = CGFloat(10)
let tip_flare = CGFloat(10)
path.move(to: CGPoint(x: start_x, y: start_y))
path.addLine(to: CGPoint(x: start_x + top_width,y: start_y))
path.addLine(to: CGPoint(x: start_x + top_width,y: start_y + tick_height))
path.addLine(to: CGPoint(x: start_x + top_width + tip_flare,y: start_y+tick_height+tip_height))
path.addLine(to: CGPoint(x: start_x - tip_flare,y: start_y + tick_height + tip_height))
path.addLine(to: CGPoint(x: start_x,y: start_y+tick_height))
path.close()
arrowLayer.path = path.cgPath
arrowLayer.fillColor = UIColor(red:0.99, green:0.13, blue:0.25, alpha:1.0).cgColor
tick?.layer.addSublayer(arrowLayer)
} else {
print(scrollView, "timeline collection view")
}
}
This draws the arrow on top of the subview beautifully.

iOS Swift 3: UICollectionView horizontal center and bigger cell

I want to build an collection view like this one:
Collection View
which has bigger cell at the center and cell is snapped to center of container view, but with Swift 3. I don't want to use library since I want to learn how to build a custom Collection View like this.
I've searched over SO but not found any appropriate solution yet
write that function
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width, height: collectionView.frame.size.height)
}
make collection view [scroll Direction] Horizontal
and [scrolling] tick scrolling enable and paging enable
make cell biger
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let offSet = self.collectionView.contentOffset
let width = self.collectionView.bounds.size.width
let index = round(offSet.x / width)
let newPoint = CGPoint(x: index * size.width, y: offSet.y)
coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) in
},completion: {(UIVIewTransitionCoordinatorContext) in
self.collectionView.reloadData()
self.collectionView.setContentOffset(newPoint, animated: true)
})
}
To achieve this you will need to subclass UICollectionViewFlowLayout and override:
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
then call super.layoutAt... and alter the cell it returns via its .transform attribute and return your altered attributes
Here is an example I made previously.
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var att = super.layoutAttributesForElements(in: rect)!
if !(delegate?.reelPlayerFlowIsPreviewMode() ?? true) {
return att
}
let region = CGRect(x: (self.collectionView?.contentOffset.x)!,
y: (self.collectionView?.contentOffset.y)!,
width: (self.collectionView?.bounds.size.width)!,
height: (self.collectionView?.bounds.size.height)!)
let center = CGPoint(x: region.midX, y: region.midY)
for theCell in att {
print("\(theCell.indexPath.item)\n\(theCell)\n")
let cell = theCell.copy() as! UICollectionViewLayoutAttributes
var f = cell.frame
let cellCenter = CGPoint(x: f.midX, y: f.midY)
let realDistance = min(center.x - cellCenter.x, region.width)
let distance = abs(realDistance)
let d = (region.width - distance) / region.width
let p = (max(d, ReelPlayerFlowLayout.minPercent) * ReelPlayerFlowLayout.maxPercent)
f.origin.x += (realDistance * ((1 - ReelPlayerFlowLayout.maxPercent) + (ReelPlayerFlowLayout.maxPercent - ReelPlayerFlowLayout.minPercent)))
cell.frame = f
cell.size = CGSize (width: f.width * p, height: f.height * p)
let index = att.index(of: theCell)!
att[index] = cell
}
return att
}

Dynamically changing CollectionView Cell Size Based on Downloaded Images Using Swift

I'm trying to build a collection view layout like Pinterest uses. Most of what is out there is in Objective C, so I've used this RW tutorial: http://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest
The problem is that the app in the RW tutorial uses local images, whereas I'm trying to base the cell size on images that are downloaded via PinRemoteImage but I cannot get the collectionView to properly lay itself out again once the images are downloaded.
Below is my attempt to modify the extension:
extension PinCollectionViewController : PinterestLayoutDelegate {
// 1
func collectionView(collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath: NSIndexPath,
withWidth width: CGFloat) -> CGFloat {
var pinterestLargestImage = UIImage()
if imageDownloads == 0 {
pinterestLargestImage = imageArray[indexPath.row]
} else {
pinterestLargestImage = UIImage(named: "testPic")!
}
let boundingRect = CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
let rect = AVMakeRectWithAspectRatioInsideRect(pinterestLargestImage.size, boundingRect)
return rect.size.height
}
// 2
func collectionView(collectionView: UICollectionView,
heightForAnnotationAtIndexPath indexPath: NSIndexPath, withWidth width: CGFloat) -> CGFloat {
var pinterestLargestImage = UIImage()
if pins.count == imageArray.count {
pinterestLargestImage = imageArray[indexPath.row]
} else { pinterestLargestImage = UIImage(named: "testPic")!}
let annotationPadding = CGFloat(4)
let annotationHeaderHeight = CGFloat(17)
let font = UIFont(name: "AvenirNext-Regular", size: 10)!
let commentHeight = CGFloat(10.0)
let height = annotationPadding + annotationHeaderHeight + commentHeight + annotationPadding
return height
}
}
Then I've tried to call self.collectionView(self.collectionView!, layout: (self.collectionView?.collectionViewLayout)!, sizeForItemAtIndexPath: indexPath) and self.collectionView!.reloadItemsAtIndexPaths([indexPath]) inside cellForRowAtIndexPath once the cell's image is downloaded, but neither properly call these methods to adjust the layout. Can anyone point me in the right direction here?

Image and scrollView rendering making my tableview choppy

There may be no good solution for my problem, but I want to ask just in case.
I have a tableview in which each cell contains a horizontal scrollview of variable width. The width of each cell's scrollview depends on the number and sizes of the images for that cell. Everything works pretty well, but the tableview scrolls less smoothly than it could. I'm using Parse to retrieve the images (and pfquertableviewcontroller), but this question should apply to tableviews in general.
Here is my tableview code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
if var cell:MainFeedTableViewCell? = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) as? MainFeedTableViewCell{
if(cell == nil) {
cell = NSBundle.mainBundle().loadNibNamed("MainFeedTableViewCell", owner: self, options: nil)[0] as? MainFeedTableViewCell
}
cell?.parseObject = object
return cell
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let c = (cell as? MainFeedTableViewCell){
c.setUpObject()//this is where images are set
}
}
override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let c = (cell as? MainFeedTableViewCell){
c.resetObject() //this sets most of the properties to nil
}
}
And here is the function in my cell where images are set
func setUpObject(){
//I left out several lines of code where label text is set from the parseObject that is set when the cell is created
//setting images **problems here**
if let numImages = self.parseObject?["numImages"] as? Int{
self.newWidth1 = self.parseObject?["width1"] as? CGFloat
self.newWidth2 = self.parseObject?["width2"] as? CGFloat
self.newWidth3 = self.parseObject?["width3"] as? CGFloat
self.newWidth4 = self.parseObject?["width4"] as? CGFloat
self.newWidth5 = self.parseObject?["width5"] as? CGFloat
if numImages == 1{
self.containerView = UIView(frame: CGRect(x: self.scrollView.frame.minX, y: self.scrollView.bounds.minY - 90, width: self.scrollView.frame.width, height: self.scrollView.frame.height))
self.image1 = PFImageView(frame: CGRect(x: self.scrollView.frame.minX , y: self.scrollView.frame.minY, width: self.scrollView.frame.width, height: self.scrollView.frame.height))
self.image1?.contentMode = UIViewContentMode.ScaleAspectFit
self.image1!.file = self.parseObject?["image"] as? PFFile
self.image1!.loadInBackground()
self.containerView!.addSubview(self.image1!)
self.scrollView.contentSize = self.containerView!.bounds.size
self.scrollView.addSubview(self.containerView!)
}
else if numImages == 2{
if self.newWidth1 + self.newWidth2 < self.scrollView.frame.width{
self.containerView = UIView(frame: CGRect(x: self.scrollView.frame.midX - (self.newWidth1 + self.newWidth2)/2, y: self.scrollView.bounds.minY - 90, width: (self.newWidth1 + self.newWidth2), height: self.scrollView.frame.height))
}
else{
self.containerView = UIView(frame: CGRect(x: self.scrollView.frame.minX, y: self.scrollView.bounds.minY - 90, width: (self.newWidth1 + self.newWidth2), height: self.scrollView.frame.height))
}
self.image1 = PFImageView(frame: CGRect(x: self.scrollView.frame.minX , y: self.scrollView.frame.minY, width: self.newWidth1, height: self.scrollView.frame.height))
self.image1!.file = self.parseObject?["image"] as? PFFile
self.image1!.loadInBackground()
self.containerView!.addSubview(self.image1!)
self.image2 = PFImageView(frame: CGRect(x: (self.scrollView.frame.minX + self.newWidth1), y: self.scrollView.frame.minY, width: self.newWidth2, height: self.scrollView.frame.height))
self.image2!.file = self.parseObject?["image2"] as? PFFile
self.image2!.loadInBackground()
self.containerView!.addSubview(self.image2!)
self.subLayer = CALayer()
self.subLayer.backgroundColor = UIColor.whiteColor().CGColor
self.subLayer.frame = CGRect(x: self.newWidth1, y: self.scrollView.frame.minY, width: 1, height: self.scrollView.frame.height)
self.containerView!.layer.addSublayer(self.subLayer)
self.scrollView.contentSize = self.containerView!.bounds.size
self.scrollView.addSubview(self.containerView!)
}
//repeat similar code for cases where there are 3, 4, or 5 images
There might be a fundamental issue with dynamically adjusting the size of the scrollview and adding it to superview just in time, but I'm trying to follow the design mockup that my designer gave me.
Here is what the scrollview on the cell looks like (with each image in the scrollview separated by a thin white line)
Remove your willDisplayCell and didEndDisplayingCell. That will fire as you scroll and your setUpObject code, while not huge, will block the main thread slightly. Instead move setUpObject() to right before returning the cell in cellForRowAtIndexPath.
Depending on how many rows you have and performance requirements you could also adjust the viewController to download all of the images ahead of time and pass them to the cell instead of loading them inside the cell.

Resources