How to avoid resizing UITextView content when applying a transform - swift

I'm making a little notes app in which i've added a textView inside each cell, when selecting a cell it scales itself to certain size so the textView is scaled too. Everything is fine except that the text inside the textView is also scaled and looks pretty bad.
Does anyone know how to prevent the text from resizing or how can i handle this issue?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as! collectionViewCell3
cell.clipsToBounds = false
cell.layer.cornerRadius = 10
noteTextView[indexPath.item].frame = CGRect(x: 10, y: 10, width: cell.frame.width - 20, height: cell.frame.height - 20)
noteTextView[indexPath.item].delegate = self
noteTextView[indexPath.item].textContainer.maximumNumberOfLines = 10
noteTextView[indexPath.item].isScrollEnabled = false
noteTextView[indexPath.item].font = UIFont(name: "Noteworthy-Light", size: 12)
noteTextView[indexPath.item].text = items[indexPath.item]
cell.contentView.addSubview(noteTextView[indexPath.item])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
index = indexPath
notasCollectionView.isScrollEnabled = false
let cell = notasCollectionView.cellForItem(at: indexPath)
let desiredPointY = notasCollectionView.contentOffset.y + 350
let desiredPointX = notasCollectionView.center.x
let differenceX = desiredPointX - cell!.frame.midX
let differenceY = desiredPointY - cell!.frame.mid
let differenceHeight = 354 / (cell?.frame.height)!
var tt = CGAffineTransform(scaleX: 1.89304813, y: differenceHeight)
tt = tt.concatenating(CGAffineTransform(translationX: differenceX, y: differenceY))
UIView.animate(withDuration: 0.2, delay: 0.0, animations: {
self.notasCollectionView.bringSubviewToFront(cell!)
cell!.transform = tt
}, completion: { _ in
UIView.animate(withDuration: 0.2) {
cell?.layer.cornerRadius = 0
}
})
}
Here are the screenshots:
[![Screenshot 1][1]][1] [![Screenshot 2][2]][2]
[1]: https://i.stack.imgur.com/cYURo.png [2]: https://i.stack.imgur.com/LbDND.jpg

The problem is you are increasing the size of the text view but the font size is the same.
So you need to change the font size according to your scaling multiplier.

Related

NSCollectionView viewForSupplementaryElementOfKind not being called

In my NSCollectionViewItem I set up the code below.
func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> NSView {
let view = collectionView.makeSupplementaryView(ofKind: .sectionHeader, withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "sectionHeader"), for: indexPath)
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.red.cgColor
return view
}
func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize {
return NSSize(width: self.frame.size.width, height: 60)
}
However, when I place a print() in the viewForSupplementaryElementOfKind function it never is executed. Also, no red header appears.
This is how I set up the NSCollectionView
public let collectionView: NSCollectionView = {
let v = NSCollectionView(frame: NSRect.zero)
v.wantsLayer = true
v.layer!.backgroundColor = NSColor.clear.cgColor
v.isSelectable = true
v.backgroundColors = [NSColor.clear]
v.allowsEmptySelection = false
v.collectionViewLayout = {
let l = NSCollectionViewFlowLayout()
l.minimumInteritemSpacing = 1
l.minimumLineSpacing = 1
l.scrollDirection = NSCollectionView.ScrollDirection.vertical
l.sectionInset = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
return l
}()
return v
}()
What am I doing wrong?
The supplemental views (header and footer) are not collection view items. You need to implement those two methods on the NSCollectionViewDelgateFlowLayout object, not on your NSCollectionViewItem class.
See https://developer.apple.com/documentation/appkit/nscollectionviewdelegateflowlayout
You can also set a default for the entire collection view:
l.headerReferenceSize = NSSize(width: 0, height: 50)
l.footerReferenceSize = NSSize(width: 0, height: 50)
When using NSCollectionViewFlowLayout, the default size of the header and footer is NSSize.zero, so the method to make the supplemental view is not called unless one of these techniques is used.

Left Align UICollectionViewCells only works when cells are not correct height, and stops working when scrolled

I am trying to left align the cells in a UICollectionView, and I have used a GitHub repo to try and obtain this, link here:
https://github.com/mischa-hildebrand/AlignedCollectionViewFlowLayout
I set up the CollectionView and its cells like so:
lazy var filterCollectionView: UICollectionView = {
let layout = AlignedCollectionViewFlowLayout(horizontalAlignment: .left, verticalAlignment: .center)
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.register(filterCell.self, forCellWithReuseIdentifier: "filterCellId")
cv.backgroundColor = .white
cv.isScrollEnabled = true
cv.dataSource = self
cv.delegate = self
cv.showsHorizontalScrollIndicator = false
return cv
}()
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return genrArray.count
}
let genArray = ["Test123", "LongTextTest", "Short", "S", "#LongLongLongLong"]
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "filterCellId", for: indexPath) as! filterCell
cell.genText.text = genArray[indexPath.row]
cell.genText.sizeToFit()
cell.frame = CGRect(x: cell.frame.origin.x, y: cell.frame.origin.y, width: cell.genText.frame.width + 25, height: 24)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let label = UILabel(frame: .zero)
label.text = genArray[indexPath.row]
label.frame = CGRect(x: 0, y: 0, width: label.intrinsicContentSize.width, height: 0)
return CGSize(width: label.frame.width + 25, height: 18)
}
This did nothing to the cells, so I added these lines of code into ViewDidLoad():
let layout = AlignedCollectionViewFlowLayout(horizontalAlignment: .left, verticalAlignment: .center)
layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
self.filterCollectionView.collectionViewLayout = layout
The line that actually made a change in the CollectionView was layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize. But this still did not achieve the desired effect. This squished my cells and made them have a height of much smaller than 18 (the size declared in sizeForItem. When loaded up, the collectionView looks like this:
But when I scroll through the collectionView, it reverts back to normal as if the left alignment layout is not even there. It then looks like this:
The cells are the correct shape in that image, but the alignment/layout/spacing is off.
What am I doing wrong?

Swift 4 - Multiple inheritance from classes 'NSObject' and 'UICollectionViewFlowLayout'

I am trying to programatically size the collection cell to be the width of the frame, however, the cell size doesn't change when I run the app. Is this the right function to call for Swift 4 and Xcode 9?
import UIKit
class SettingsLauncher: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewFlowLayout {
let blackView = UIView()
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.white
return cv
}()
let cellID = "cell"
#objc func showMenu() {
// Show menu
if let window = UIApplication.shared.keyWindow { // Get the size of the entire window
blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
let height: CGFloat = 200
let y = window.frame.height - height // The y value to appear at the bottom of the screen
collectionView.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: height)
// Add gesture recognizer on black view to dismiss menu
blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))
window.addSubview(blackView)
window.addSubview(collectionView)
blackView.frame = window.frame
blackView.alpha = 0
// Slow the animation down towards the end (curveEasOut)
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
// Animate black view
self.blackView.alpha = 1
// Animate collection view
self.collectionView.frame = CGRect(x: 0, y: y, width: self.collectionView.frame.width, height: height)
}, completion: nil)
}
}
#objc func handleDismiss() {
// Dimisses menu view
UIView.animate(withDuration: 0.5) {
self.blackView.alpha = 0
if let window = UIApplication.shared.keyWindow {
self.collectionView.frame = CGRect(x: 0, y: window.frame.height, width: self.collectionView.frame.width, height: self.collectionView.frame.height)
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 50)
}
override init() {
super.init()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(MenuCell.self, forCellWithReuseIdentifier: cellID)
}
}
Edit:
This table view is being animated from the bottom of the page and presents a collection view, which is being called from the view controller that is using the pop up menu.
I now get the error:
Multiple inheritance from classes 'NSObject' and 'UICollectionViewFlowLayout'
UICollectionViewFlowLayout is not a protocol, it's a class. You need to use UICollectionViewDelegateFlowLayout instead of UICollectionViewFlowLayout.
Change
class SettingsLauncher: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewFlowLayout
to
class SettingsLauncher: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

UICollectionView equal cell spacing

I am displaying several images in a collection view. They are all the same orientation (landscape) except for one, which is portrait (see image below):
I am trying to make the portrait image more centered, so that everything is evenly spaced. Any ideas on how to do this?
PhotoGalleryViewController.swift:
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoGalleryCell
let image = UIImage(named: images[indexPath.row])
cell.imageView.image = image
cell.captionLabel.text = captions[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var size = CGSize()
if (indexPath.row == 3)
{
size = CGSize(width: 450, height: 600)
}
else {
size = CGSize(width: 940, height: 600)
}
return size
}
My suggestion would be not altering the cell size based on the fact that a portrait image will be in item 3.
Instead update the layout of your cell so that whatever image it gets assigned to it's image view, it will centre the image in itself and centralise the label underneath the image.
In ViewDidLoad method put this code :
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionview.collectionViewLayout = layout
Also add this into cellForRow Methods:
cell.imageview.contentmode = .aspectfit
Hope it helps to resolve your issue.

Estimating size of UICollectionView cell for some text

So I'm creating a messaging type app, which consists of some blocks of UITextView containing varying lengths of text and these reside in a "bubble" UIView.
let textView: UITextView = {
let text = UITextView()
text.text = "SAMPLE"
text.translatesAutoresizingMaskIntoConstraints = false
text.backgroundColor = .clear
text.textColor = .white
return text
}()
let bubbleView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(r: 0, g: 137, b: 247)
view.layer.cornerRadius = 14
view.layer.masksToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var bubbleWidthAnchor: NSLayoutConstraint?
bubbleView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
bubbleView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
bubbleWidthAnchor = bubbleView.widthAnchor.constraint(equalToConstant: 250)
bubbleWidthAnchor?.isActive = true
bubbleView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
textView.leftAnchor.constraint(equalTo: bubbleView.leftAnchor, constant: 8).isActive = true
textView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
textView.rightAnchor.constraint(equalTo: bubbleView.rightAnchor).isActive = true
textView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
To set the height of the cell I am using a custom function which is supposed to not working properly.
Custom function:
private func estimatedFrameForText(text: String) -> CGRect {
let size = CGSize(width: 250, height: 250)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
return NSString(string: text).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)], context: nil)
}
Which I call in the sizeForItemAt function for UICollectionView:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var height: CGFloat = 80 //Arbitrary number
if let text = messages[indexPath.item].text {
height = estimatedFrameForText(text: text).height + 8
}
return CGSize(width: view.frame.width, height: height)
}
The simple problem I am having is... it does not working great:
Example
Any idea where I am going wrong, or a better solution to getting the estimated size I need for the cell, depending on the text?
As it turns out, all that I was missing was to set the text size in the textView.
Putting text.font = UIFont.systemFont(ofSize: 16) in was required because the function to get the estimated size has:
attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)
So you have to define both to be the same.
Swift 4.2 updated answer is to handle height and width of uicollectionviewCell on the basis of uilabel
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
let size = (self.FILTERTitles[indexPath.row] as NSString).size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14.0)])
return CGSize(width: size.width + 38.0, height: size.height + 25.0)
}