UICollectionView lags when scroll - swift

I have a UICollectionView where i display cell that contain an png image each cell. When i display two er more cell beside each other the scroll will lag, but when i only display cells below eachother the scroll run more smotthly.
In my cellForItemAtIndexPath i got this 2 lines of coe which was recommended in another stackoverflow thread:
cell.layer.shouldRasterize = true;
cell.layer.rasterizationScale = UIScreen.mainScreen().scale
It did help a little, but not much.
The way i get the image is by making an extension to ImageView:
import Foundation
import Alamofire
let imageCache = NSCache()
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let image = imageCache.objectForKey(urlString) as? UIImage {
self.image = nil
self.image = image
}
else {
self.image = nil
Alamofire.request(.GET, urlString).responseJSON{
response in
if let tilbudimage = UIImage(data: response.data!){
self.image = tilbudimage
imageCache.setObject(tilbudimage, forKey: urlString)
}
}
}
}
}
And in my cellForItemAtIndexPath i init the cell image like:
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("postcol", forIndexPath: indexPath) as! PostColViewCell
cell.PostImg.imageFromUrl(firstImage["imgurl"].string!)
Display cells this way lag when scroll:
Display cells this way does not lag when scroll
Here is my whole cellForItemAtIndexPath:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("postcol", forIndexPath: indexPath) as! PostColViewCell
cell.layer.shouldRasterize = true;
cell.layer.rasterizationScale = UIScreen.mainScreen().scale
cell.layer.cornerRadius = 10
let post = self.postArray[indexPath.row]
let firstImage = post["images"].array![0]
if(post["newpost"].int! <= 1)
{
cell.NewLabel.hidden = false
}
else
{
cell.NewLabel.hidden = true
}
cell.ProfilePicture.imageFromUrl(post["user"]["photourl"].string!)
cell.ProfilePicture.contentMode = .ScaleAspectFill
cell.ProfilePicture.clipsToBounds = true
cell.NameLabel.text = post["user"]["firstname"].string! + " " + post["user"]["lastname"].string!
cell.PriceLabel.text = String(post["price"].int!) + " kr."
cell.NameLabel?.userInteractionEnabled = true
cell.NameLabel?.tag = indexPath.row
let tapped:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "seeUser:")
tapped.numberOfTapsRequired = 1
cell.NameLabel?.addGestureRecognizer(tapped)
cell.TitleText.textColor = UIColor.blackColor()
cell.TitleText.labelSpacing = 5; // distance between start and end labels
cell.TitleText.pauseInterval = 2.0; // seconds of pause before scrolling starts again
cell.TitleText.scrollSpeed = 30; // pixels per second
cell.TitleText.textAlignment = NSTextAlignment.Left; //centers text when no auto-scrolling is applied
cell.TitleText.fadeLength = 12;// length of the left and right edge fade, 0 to disable
cell.TitleText.font = UIFont(name: (cell.TitleText?.font.fontName)!, size: 12)!
cell.TitleText.text = post["title"].string!
if(cell.PostImg.image != nil)
{
cell.PostImg.imageFromUrl(firstImage["imgurl"].string!)
}
cell.PostImg.contentMode = .ScaleAspectFill
cell.PostImg.clipsToBounds = true
//Comment label layout
cell.CommentLabel.text = String(post["comments"].array!.count)
cell.CommentLabel.textColor = UIColor.whiteColor()
// Here is the magic
cell.CommentLabel.icon = UIImage(named: "Comment")// Set icon image
cell.CommentLabel.icon = cell.CommentLabel.icon!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
cell.CommentLabel.tintColor = UIColor.whiteColor()
cell.CommentLabel.iconPadding = 5 // Set padding between icon and label
cell.CommentLabel.iconPosition = SMIconLabelPosition.Left // Icon position
cell.CommentLabel.textAlignment = .Right
//Distance label layout
if (post["distance"].double! < 1)
{
cell.DistanceLabel.text = LoginViewController.CurrentUser.CurrentLocation
}
else
{
let formatter = NSNumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 0
cell.DistanceLabel.text = formatter.stringFromNumber(post["distance"].double!)! + " km"
}
cell.DistanceLabel.textColor = UIColor.whiteColor()
// Here is the magic
cell.DistanceLabel.icon = UIImage(named: "Location")// Set icon image
cell.DistanceLabel.icon = cell.DistanceLabel.icon!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
cell.DistanceLabel.tintColor = UIColor.whiteColor()
cell.DistanceLabel.iconPadding = 0 // Set padding between icon and label
cell.DistanceLabel.iconPosition = SMIconLabelPosition.Left // Icon position
cell.DistanceLabel.textAlignment = .Left
return cell
}

Related

UIImage and UILabel disappearing after doing UIRefreshControl

UIImages and UILabel are disappearing in some collectionViews after refreshing inside my app.
here is my code. You can see what is wrong in the picture, the left image is before refreshing and there is a discount price label and after refreshing the simulator, it is gone. getProductLatestData(), getBestSellingData() are the Alamofire get request for API.
//For Refresh Controller
//----------------------
var player : AVAudioPlayer
var refreshController : UIRefreshControl = {
let refreshController = UIRefreshControl()
refreshController.addTarget(self, action: #selector(updateData), for: .valueChanged)
return refreshController
}()
//----------------------
//For Update Data when scroll to top
//----------------------------------
#objc func updateData(){
//To play sound when scroll top
//-----------------------------
let pathToSound = Bundle.main.path(forResource: "Flick", ofType: "wav")
let url = URL(fileURLWithPath: pathToSound!)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch let error {
print(error.localizedDescription)
}
//-----------------------------
//Fetch Latest Products Data
getProductLatestData(pageNumber: 0, pageSize: 0)
//Fetch BestSelling Products Data
getBestSellingData(pageNumber: 0, pageSize: 0)
//Fetch Promotion Products Data
getPromotionProductsData(pageNumber: 0, pageSize: 0)
//Fetch Products By Category
getProductsByCat(pageNumber: 0, pageSize: 0)
//Fetch Reward Products
getRewardProducts()
self.refreshController.endRefreshing()
}
if collectionView == latestItemCV {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "latestItemCell", for: indexPath) as! PromotionItemsCollectionViewCell
if let percent = latestItemData[indexPath.row].promotePercent {
if percent != 0 {
cell.percentOff.isHidden = false
cell.percentOff.text = " \(percent) % Off "
cell.percentOffBackground.isHidden = false
}
else{
cell.percentOff.isHidden = true
cell.percentOffBackground.isHidden = true
}
}
if let name = latestItemData[indexPath.row].name {
cell.itemsName.text = name
}
else{
cell.itemsName.text = "-"
}
if let url = latestItemData[indexPath.row].url {
cell.itemsImageView.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named: "placeholder"))
}
//----------------------------------
Thanks to #larme I recheck the code here is how I fixed it, I added those disappeared labels isHidden = false also as I did isHidden = true for them.
if let promotionPrice = latestItemData[indexPath.row].promotePrice {
if promotionPrice != 0 {
cell.originalItemsPrice.text = "\(setCommaForPrice(price: Int(promotionPrice))) Ks"
cell.promotionPercent.isHidden = false
cell.promotionLine.isHidden = false
}
else{
if let orPrice = latestItemData[indexPath.row].originalPrice {
cell.originalItemsPrice.text = "\(setCommaForPrice(price: Int(orPrice))) Ks"
}
cell.promotionPercent.isHidden = true
cell.promotionLine.isHidden = true
}
}

Modify cell contents in tableview after clicking in Swift

I have a chat app with 2 custom cells, sender and receiver cell. Once the cells are populated, only the ones with "show image" text can be clicked. I am trying to click on these cells so that
i can hide the label
I can show the image from the url
The tap function works but i am not able to do the above steps. Kindly help because i do not know how to go about this
Here is my code
#objc
func tapFunctionCell(sender:UITapGestureRecognizer) {
print("tap again sen")
let tapLocation = sender.location(in: tblViewChat)
let indexPath = self.tblViewChat.indexPathForRow(at: tapLocation)
let position = indexPath?.row ?? 0
print(position)
let cell = tblViewChat.dequeueReusableCell(withIdentifier: "senderCell") as! SenderTblCell
cell.lblMessage.isHidden = true
let url = URL(string:objChatVM.getMessage(index:position))
print(url)
cell.ImageB.kf.setImage(with:url)
cell.ImageB.isHidden = false
}
#objc
func tapFunction(sender:UITapGestureRecognizer) {
print("tap again receive")
let cell2 = tblViewChat.dequeueReusableCell(withIdentifier: "receiverCell") as! ReceiverTblCell
cell2.lblMessage.isHidden = false
let tapLocation = sender.location(in: tblViewChat)
let indexPath = self.tblViewChat.indexPathForRow(at: tapLocation)
let position = indexPath?.row ?? 0
print(position)
let url = URL(string:objChatVM.getMessage(index:position))
print(url)
cell2.imageButton.kf.setImage(with:url)
cell2.imageButton.isHidden = false
}
Issues in your tap function code. When you want to get a cell from the index path use the cellForRow method of table view. so instead of this
let cell = tblViewChat.dequeueReusableCell(withIdentifier: "senderCell") as! SenderTblCell
use this for both tap action.
let cell = tblViewChat.cellForRow(at: indexPath) as! SenderTblCell

TableView for Messaging App Not Updating Cells when retrieveMessages() is Called. Swift 4 & Firebase

The app allows users to have their own chat bubble colors and avatars. My issue is that when I send the message from another device, and I receive the message, my SENT cell bubble color and avatar changes. But the text remains correct. But when I move the cell out of the view, and bring it back, it changes to the correct color/avatar. Adding reloadData to the retrieveMessages() doesn't help, only cause the cells to flash quickly.
This is how I am receiving the messages
func retrieveMessages() {
let messageDB = Database.database().reference().child("ChatRooms").child(chatRoomID).child("Messages")
messageDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String,Any>
let message = snapshotValue["MessageBody"]! as! String
let sentby = snapshotValue["Sender"]! as! String
let sentUid = snapshotValue["userID"]! as! String
let messageObject = Message()
messageObject.messageBody = message
messageObject.sender = sentby
messageObject.userID = sentUid
messageObject.key = snapshot.key
self.messageArray.append(messageObject)
self.configureTableView()
let indexPath: IndexPath = IndexPath(row: self.messageArray.count - 1, section: 0)
self.messageTableView.insertRows(at: [indexPath], with: .left)
self.scrollToBottom()
}
}
This is my cellForRowAt. (I understand it's a little long. Still need to refactor what I can)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath) as! CustomMessageCell
configureTableView()
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gestureReconizer:)))
lpgr.minimumPressDuration = 0.5
lpgr.delaysTouchesBegan = true
lpgr.delegate = self
cell.addGestureRecognizer(lpgr)
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(gestureReconizer:)))
tap.delegate = self
tap.numberOfTapsRequired = 2
tap.delaysTouchesBegan = true
cell.messageBackground.addGestureRecognizer(tap)
let messageIndex = messageArray[indexPath.row]
cell.messageBody.text = messageIndex.messageBody
cell.avatar = self.myAvatar
cell.senderUsername.text = messageIndex.sender
cell.avatarImageView.image = UIImage(named: myAvatar)
cell.selectionStyle = .none
cell.likeButtonContraint.constant = 400
if likedMessagesArray.contains(messageIndex.key) {
cell.likeButton.layer.opacity = 100
cell.likeButtonContraint.constant = 2
cell.likeButton.isHidden = false
} else {
cell.likeButtonContraint.constant = 400
cell.layoutIfNeeded()
}
if self.blockedUsersArray.contains(messageArray[indexPath.row].userID) {
self.messageArray.remove(at: indexPath.row)
self.messageTableView.reloadData()
print("User \(messageIndex.sender) is blocked")
} else {
print("User \(messageIndex.sender) not blocked")
}
var color: String?
color = self.myColor
switch color {
case "red" : cell.messageBackground.backgroundColor = UIColor.flatRed()
case "gray": cell.messageBackground.backgroundColor = UIColor.flatGray()
case "lime": cell.messageBackground.backgroundColor = UIColor.flatLime()
case "mint": cell.messageBackground.backgroundColor = UIColor.flatMint()
case "coffee": cell.messageBackground.backgroundColor = UIColor.flatCoffee()
case "pink": cell.messageBackground.backgroundColor = UIColor.flatPink()
default: cell.messageBackground.backgroundColor = UIColor.gray
}
cell.avatarImageView.image = UIImage(named: self.myAvatar)
cell.avatarImageView.backgroundColor = UIColor.white
cell.messageBackground.layer.opacity = 82
cell.messageBackground.frame.size.width = view.frame.size.width
cell.contentView.transform = CGAffineTransform(scaleX: -1, y: 1)
cell.messageBackground.transform = CGAffineTransform(scaleX: -1, y: 1)
if cell.senderUsername.text != Auth.auth().currentUser!.email {
let messageDB = Database.database().reference().child("Users").child(messageIndex.userID)
messageDB.observe(.value) { (snapshot) in
let snapshotValue = snapshot.value as? NSDictionary
let avatar = snapshotValue!["avatar"]! as! String
cell.avatarImageView.image! = UIImage(named: avatar)!
var color: String?
let chatColor = snapshotValue!["chatColor"] as! String
color = chatColor
switch color {
case "red" : cell.messageBackground.backgroundColor = UIColor.flatRed()
case "gray": cell.messageBackground.backgroundColor = UIColor.flatGray()
case "lime": cell.messageBackground.backgroundColor = UIColor.flatLime()
case "mint": cell.messageBackground.backgroundColor = UIColor.flatMint()
case "coffee": cell.messageBackground.backgroundColor = UIColor.flatCoffee()
case "pink": cell.messageBackground.backgroundColor = UIColor.flatPink()
default: cell.messageBackground.backgroundColor = UIColor.gray
}
}
cell.avatarImageView.backgroundColor = UIColor.white
cell.messageBackground.layer.opacity = 82
cell.contentView.transform = CGAffineTransform(scaleX: 1, y: 1)
cell.messageBackground.transform = CGAffineTransform(scaleX: 1, y: 1)
}
return cell
}
Before Receiving Message. Freshly loaded
After Receiving Message, but notice the text stays correct. But my cell changes it's bubble color and avatar
Moved cell out of view
Brought cell back, cell changes to correct color, avatar
I think that you have to add reloadData method at the end of retrieveMessages()
self.messageTableView.reloadData()

ALAMOFIRE post request image download and binding in a UICollectionView

I need to download images I created a alamofire post request with parameter i dont have any problem in that . After that i need to download the image url from the Json response generated, I dont know how to download the image url from json and keep that in a array , after that have to download the inage from the url need to bind it in a image view of collectionView . I dont have any idea about how to take the image url from the json response then keep that in a array , then have to download the image bind it in a collectionView. Please help me
I have updated the json response for my post request. please give me a solution. I can get the below response in console.
( {
ActualPrice = 0;
AssuredTitle = "<null>";
CashBackAmount = 0;
CashBackDiscountPercentage = 0;
Code = "";
Cost = "<null>";
CreateDate = "<null>";
CustomSize = 0;
Delivery = "<null>";
DeliveryDate = "<null>";
DeliveryDays = "<null>";
Designer = "<null>";
Discount = "<null>";
DiscountCost = "<null>";
DispatchDateDisplay = "<null>";
Exclusive = "<null>";
Gender = "<null>";
HasReadyMadeColor = 0;
HasReadyMadeSizes = 0;
ID = 41;
ImageUrl = "https://images.cbazaar.com/images/aqua-blue-georgette-abaya-isbs1805991-u.jpg";
Is7DD = "<null>";
IsCustomizable = 0;
IsExclusive = 0;
IsFree = "<null>";
IsFreeShipping = 0;
IsInWishlist = 0;
IsLookUp = 0;
IsNew = 0;
IsProductAnimation = 0;
IsReadyToShip = 0;
LargeImageUrl = "<null>";
ListingImage = "<null>";
LowerLargeImage = "<null>";
LowerThumbImage = "<null>";
MoneyFactor = "<null>";
MoneyOffFactor = "<null>";
Name = "Islamic wear";
OfferImageUrl = "<null>";
OldPrice = 0;
OutOfStock = 0;
PDUrl = "<null>";
ProductBigLink = "<null>";
ProductCollectionReference = "<null>";
ProductHisImage = "<null>";
ProductSaleCycle = 0;
ProductType = 168;
ProductV2VRatio = 0;
PromotionTypeID = "<null>";
Promotions = "<null>";
PromotionsIcon = "<null>";
Rating = "<null>";
SalePrice = "<null>";
ShowOldPrice = 0;
SizeChart = "<null>";
SuperClassification = "<null>";
TypeGroup = "<null>";
TypeShortCode = "<null>";
UpperLargeImage = "<null>";
UpperThumbImage = "<null>";
VendorType = "<null>";
VisitCount = 0;
})
Complete ViewController File
import UIKit
import Alamofire
import AlamofireImage
class EthnoVogueDesignConsultationViewController: UIViewController, UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var header_scrollView: UIScrollView!
#IBOutlet weak var pagecontroller: UIPageControl!
#IBOutlet weak var step_label: UILabel!
#IBOutlet weak var segmented_View: UIView!
#IBOutlet weak var segmented_Control: UISegmentedControl!
#IBOutlet weak var stylistView: UIView!
#IBOutlet weak var categorycollectionview: UICollectionView!
#IBOutlet weak var pagecontrollerview: UIView!
let image_array = ["slider1","slider2","slider1","slider2"]
let name_label = ["Salwar kameez","saree", "Anarkali", "Leghenga"]
static var deepLinkingFlag:Int = 0
static var deepLinkingFlagAfterKilling:Int = 0
var httpObj = HTTPHelper()
var apiRequestParameters:NSMutableDictionary = NSMutableDictionary()
var dictResult: NSDictionary = NSDictionary()
// var imageCache = [String:UIImage]()
//Array of images from the URL
var imageArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
globalConstants.deepLinkingFlagAfterKilling = 0
globalConstants.deepLinkingFlag = 0
apiclass()
// imagedownload()
//View which holds the stylist Name
stylistView.backgroundColor = UIColor(red: 235/255, green: 232/255, blue: 232/255, alpha: 1)
pagecontrollerview.backgroundColor = UIColor(red: 235/255, green: 232/255, blue: 232/255, alpha: 1)
//Label with holds the step 1
step_label.layer.borderWidth = 2
step_label.layer.borderColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
stylistView.layer.shadowOffset = CGSize(width: 1, height: 1)
step_label.layer.shadowOpacity = 4
step_label.layer.shadowColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
//Customising the segmented control with background color and tint color, font size
segmented_Control.tintColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1)
segmented_Control.backgroundColor = UIColor.white
segmented_Control.layer.cornerRadius = 20
// let font = UIFont.systemFont(ofSize: 20)
let font = UIFont.boldSystemFont(ofSize: 20)
segmented_Control.setTitleTextAttributes([NSAttributedStringKey.font: font],
for: .normal)
let cellSize = CGSize(width:250 , height:400)
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = cellSize
layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
layout.minimumLineSpacing = 10.0
layout.minimumInteritemSpacing = 10.0
categorycollectionview.setCollectionViewLayout(layout, animated: true)
categorycollectionview.setCollectionViewLayout(layout, animated: false)
categorycollectionview.delegate = self
categorycollectionview.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
self.header_scrollView.frame = CGRect(x:0, y:0, width:self.view.frame.width, height:225)
let scrollViewWidth:CGFloat = self.header_scrollView.frame.width
let scrollViewHeight:CGFloat = self.header_scrollView.frame.height
header_scrollView.backgroundColor = UIColor.black
//set image to the particular image in uiscrollview
let imgOne = UIImageView(frame: CGRect(x:0, y:0,width:scrollViewWidth, height:scrollViewHeight))
imgOne.image = UIImage(named: "slider2")
let imgTwo = UIImageView(frame: CGRect(x:scrollViewWidth, y:0,width:scrollViewWidth, height:scrollViewHeight))
imgTwo.image = UIImage(named: "slider1")
//Adding subview for the scrollview
self.header_scrollView.addSubview(imgOne)
self.header_scrollView.addSubview(imgTwo)
//setting size of the content view
self.header_scrollView.contentSize = CGSize(width:self.header_scrollView.frame.width * 4, height:self.header_scrollView.frame.height)
//header scroll view delegate selection
self.header_scrollView.delegate = self
self.pagecontroller.currentPage = 0
// time interval to move the slide show
Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(moveToNextPage), userInfo: nil, repeats: true)
//step label for rounded corners
step_label.layer.masksToBounds = true
step_label.layer.cornerRadius = 15.0
NotificationCenter.default.addObserver(self, selector: #selector(EthnoVogueDesignConsultationViewController.deepLinking(_:)), name:NSNotification.Name(rawValue: "deepLinking"), object: nil)
}
#objc func deepLinking(_ notification:Notification){
print("its here")
// globalConstants.isSortCleared = 0
if(globalConstants.deepLinkingFlag == 1){
self.tabBarController?.selectedIndex = 0
// let viewController = self.storyboard?.instantiateViewController(withIdentifier:"catalog") as? CatalogController
// self.navigationController?.pushViewController(viewController!, animated: false)
}
else if(globalConstants.deepLinkingFlag == 2){
self.tabBarController?.selectedIndex = 0
// let viewController = self.storyboard?.instantiateViewController(withIdentifier:"productDetails") as? ProductDetailViewController
// self.navigationController?.pushViewController(viewController!, animated: false)
}
else if(globalConstants.deepLinkingFlag == 3){
self.tabBarController?.selectedIndex = 0
// let viewController = self.storyboard?.instantiateViewController(withIdentifier:"ols") as? OLSViewController
// self.navigationController?.pushViewController(viewController!, animated: false)
}
else if(globalConstants.deepLinkingFlag == 4){
self.tabBarController?.selectedIndex = 0
// let viewController = self.storyboard?.instantiateViewController(withIdentifier:"home") as? HomeController
// self.navigationController?.pushViewController(viewController!, animated: false)
}
else if(globalConstants.deepLinkingFlag == 5){
//self.navigationController?.popToRootViewControllerAnimated(false)
self.tabBarController?.selectedIndex = 1
}
else if(globalConstants.deepLinkingFlag == 6){
//self.navigationController?.popToRootViewControllerAnimated(false)
self.tabBarController?.selectedIndex = 2
}
else if(globalConstants.deepLinkingFlag == 7){
//self.navigationController?.popToRootViewControllerAnimated(false)
self.tabBarController?.selectedIndex = 0
}
}
// move to next image image view in file
#objc func moveToNextPage (){
let pageWidth:CGFloat = self.header_scrollView.frame.width
let maxWidth:CGFloat = pageWidth * 2
let contentOffset:CGFloat = self.header_scrollView.contentOffset.x
var slideToX = contentOffset + pageWidth
if contentOffset + pageWidth == maxWidth
{
slideToX = 0
}
self.header_scrollView.scrollRectToVisible(CGRect(x:slideToX, y:0, width:pageWidth, height:self.header_scrollView.frame.height), animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//scrollView Method for chaning the page control while swiping the image
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pagenumber = scrollView.contentOffset.x / scrollView.frame.size.width
pagecontroller.currentPage = Int(pagenumber)
}
//CollectionView for Categories image
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch segmented_Control.selectedSegmentIndex {
case 0:
return imageArray.count
case 1:
return 10
default:
break
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let Cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imagecell", for: indexPath) as! CategorySegmentCollectionViewCell
let url = NSURL(string: self.imageArray[indexPath.item])!
Cell.category_image.af_setImage(withURL: url as URL, placeholderImage: UIImage(named: "noimage.png"), filter: nil, imageTransition: .noTransition, runImageTransitionIfCached: true, completion: nil)
switch segmented_Control.selectedSegmentIndex{
case 0:
// let img : UIImage = UIImage(named:"pink")!
//
// Cell.category_image.image = img
// Cell.category_name_label.text = name_label[indexPath.item]
break
case 1:
// let img : UIImage = UIImage(named:"dark")!
// Cell.category_image.image = img
// Cell.category_name_label.text = "condition"
break
default:
break
}
//let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "brandCell", for: indexPath) as! BrandCollectionViewCell
// use this to download images
return Cell
}
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.5) {
if let cell = collectionView.cellForItem(at: indexPath) as? CategorySegmentCollectionViewCell {
cell.category_image.transform = .init(scaleX: 0.95, y: 0.95)
cell.contentView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
}
}
}
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.5) {
if let cell = collectionView.cellForItem(at: indexPath) as? CategorySegmentCollectionViewCell {
cell.category_image.transform = .identity
cell.contentView.backgroundColor = .clear
}
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch segmented_Control.selectedSegmentIndex{
case 0:
if (collectionView.cellForItem(at: indexPath) as? CategorySegmentCollectionViewCell) != nil {
self.segmented_Control.setEnabled(true, forSegmentAt: 1)
segmented_Control.selectedSegmentIndex = 1
collectionView.reloadData()
//print(cell)
}
break
case 1:
if (collectionView.cellForItem(at: indexPath) as? CategorySegmentCollectionViewCell) != nil {
self.segmented_Control.setEnabled(true, forSegmentAt: 2)
let categoryTaskVC = storyboard?.instantiateViewController(withIdentifier: "fabrics") as! FabricsViewController
self.navigationController?.pushViewController(categoryTaskVC, animated: true)
}
break
default:
break
}
}
override func viewWillAppear(_ animated: Bool) {
if(segmented_Control.selectedSegmentIndex == 0){
self.segmented_Control.setEnabled(false, forSegmentAt: 1)
self.segmented_Control.setEnabled(false, forSegmentAt: 2)
}
}
#IBAction func segmented_tapped_action(_ sender: Any) {
categorycollectionview.reloadData()
}
func apiclass(){
if(globalConstants.prefs.value(forKey: "authToken") == nil){
self.httpObj.getAuthToken()
}
else if(globalConstants.prefs.value(forKey: "authExpireDate") != nil && Date().compare((globalConstants.prefs.value(forKey: "authExpireDate") as? Date)!) == ComparisonResult.orderedDescending){
globalConstants.prefs.setValue(nil, forKey: "authToken")
self.httpObj.getAuthToken()
}
DispatchQueue.main.async(execute: {
if(globalConstants.prefs.value(forKey: "authToken") != nil){
var request:NSMutableURLRequest = NSMutableURLRequest(url: globalConstants.tokenUrl as URL)
let authToken:String = (globalConstants.prefs.value(forKey: "authToken") as? String)!
request = NSMutableURLRequest(url: globalConstants.tokenUrl as URL)
request.addValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
request.addValue(UIDevice.current.identifierForVendor!.uuidString, forHTTPHeaderField: "X-Device-ID")
request.addValue((globalConstants.prefs.value(forKey: "UUID") as? String)!, forHTTPHeaderField: "X-Unique-ID")
request.addValue((globalConstants.prefs.value(forKey: "countryCode") as? String)!, forHTTPHeaderField: "X-Country-Code")
request.addValue((globalConstants.prefs.value(forKey: "currencyCode") as? String)!, forHTTPHeaderField: "X-Currency-Code")
request.addValue((globalConstants.prefs.value(forKey: "currencySymbol") as? String)!, forHTTPHeaderField: "X-Currency-Symbol")
request.addValue(String(stringInterpolationSegment: (globalConstants.prefs.value(forKey: "currencyFactor"))!), forHTTPHeaderField: "X-Currency-Factor")
request.addValue((globalConstants.prefs.value(forKey: "appSource") as? String)!, forHTTPHeaderField: "X-App-Source")
request.addValue(globalConstants.appVersion, forHTTPHeaderField: "X-App-Version")
request.addValue(String(stringInterpolationSegment: (globalConstants.prefs.value(forKey: "estoreId") as? Int)!), forHTTPHeaderField: "X-EStore-ID")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
if(globalConstants.prefs.value(forKey: "userEmail") != nil){
request.addValue((globalConstants.prefs.value(forKey: "userEmail") as? String)!, forHTTPHeaderField: "X-Email")
}
if(globalConstants.prefs.value(forKey: "userId") != nil){
request.addValue(String(stringInterpolationSegment: (globalConstants.prefs.value(forKey: "userId"))!), forHTTPHeaderField: "X-User-ID")
}
print(self.apiRequestParameters)
var requestParameters:NSMutableDictionary = NSMutableDictionary()
requestParameters = [
"mode" : "design",
"productGroup" : 0
]
print(requestParameters)
request.url = globalConstants.ESDCUrl as URL
self.httpObj.sendRequest("POST", requestDict: requestParameters, request: request as URLRequest, completion: { (result, error) in
print(result!)
if(error == nil){
guard let json = result as! [[String:Any]]? else{
return
}
print("Response \(json)")
for images in json
{
if let ImageUrl = images["ImageUrl"] as? String
{
self.imageArray.append(ImageUrl)
}
DispatchQueue.main.async {
self.categorycollectionview.reloadData()
}
}
// self.dictResult = result as! NSDictionary
// self.categorycollectionview.reloadData()
//self.collectionView.reloadData()
// let requestDataDict:NSDictionary = incomingRequetArray[0] as! NSDictionary
// let newDict: NSURL = requestDataDict.object(forKey: "ImageUrl") as? NSDictionary
//
}
else{
let alert = UIAlertView()
alert.isHidden = true
alert.addButton(withTitle: "OK")
alert.message = globalConstants.apiErrorMessage
alert.show()
}
})
}
})
}
//typealaising the headerscrollview to the view controller
private typealias Header_scrollView = EthnoVogueDesignConsultationViewController
// extending the header_scrollview
extension Header_scrollView
{
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView){
// Test the offset and calculate the current page after scrolling ends
let pageWidth:CGFloat = scrollView.frame.width
let currentPage:CGFloat = floor((scrollView.contentOffset.x-pageWidth/2)/pageWidth)+1
// Change the indicator
self.pagecontroller.currentPage = Int(currentPage);
UIView.animate(withDuration: 1.0, animations: { () -> Void in
// self.startButton.alpha = 1.0
})
}
}

TableView cell messing up constraints

I've a tableView where I present news feed from my Database. The amount of cells right now is around 20 but it will continue to grow for sure.
In a cell I've three labels: Title, Date and a short description. I've set up all of my constraints using storyboards. And the height of my tableView cell is dynamically changing according to the size of my content.
The problem is whenever I load my feed, one of the cells is always messed up. There is a constraint between Title label and date label >=30 so it's always at least one cell that will have a title label with a constant width of 190 (the others are always correctly displayed). If I scroll my tableView up and return back to that cell it will come back to normal but the height of the cell will stay the same (too big for the content).
What can be causing the problem?
Thank you in advance!
Edit:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath)
let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as! FinalNews
cell.backgroundColor = UIColor(red: 249/255, green: 237/255, blue: 229/255, alpha: 1)
let chevron = UIImage(named: "Next4.png")
cell.accessoryType = .DisclosureIndicator
cell.accessoryView = UIImageView(image: chevron!)
cell.textLabel?.textColor = UIColor.blackColor()
// Feeds dictionary.
var dict : NSDictionary! = myFeed.objectAtIndex(indexPath.row) as! NSDictionary
let firstiteration: String = (myFeed.objectAtIndex(indexPath.row).objectForKey("Description")?.stringByReplacingOccurrencesOfString("<b>", withString: ""))!
let seconditeration = firstiteration.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
let category: String = myFeed[indexPath.row].objectForKey("CategoryID") as! String
func getCategory(value: String) -> String {
var end = value.endIndex
for var i = value.startIndex;
i < value.endIndex;
i = i.successor() {
if value[i] == "\n" {
end = i
break
}
}
return value[value.startIndex..<end]
}
let counter1 = getCategory(category)
if counter1 == "1"{
cell.titleLabel.text = myFeed.objectAtIndex(indexPath.row).objectForKey("DosNum") as? String
cell.descLabel.text = " \n "
cell.descLabel.textColor = UIColor(red: 249/255, green: 237/255, blue: 229/255, alpha: 1)
cell.dateLabel.text = myFeed.objectAtIndex(indexPath.row).objectForKey("Date_text") as? String
}
else{
cell.titleLabel.text = myFeed.objectAtIndex(indexPath.row).objectForKey("Title") as? String
cell.descLabel.text = seconditeration
cell.descLabel.textColor = UIColor.blackColor()
cell.dateLabel.text = myFeed.objectAtIndex(indexPath.row).objectForKey("Date_text") as? String
}
var shorDate: String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.stringFromDate(NSDate())
}
let today1 = shorDate
let dateIter = myFeed.objectAtIndex(indexPath.row).objectForKey("Date_publication") as? String
let dateIter1: String = (dateIter as? NSString)!.substringToIndex(10)
let calendar = NSCalendar.currentCalendar()
//let twoDaysAgo = calendar.dateByAddingUnit(.Day, value: -1, toDate: NSDate(), options: [])
var shorDate1: String {
let dateFormatter = NSDateFormatter()
let oneDaysAgo = calendar.dateByAddingUnit(.Day, value: -1, toDate: NSDate(), options: [])
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.stringFromDate(oneDaysAgo!)
}
let oneDaysAgo1 = shorDate1
if today1 == dateIter1{
cell.dateLabel.text = "Сегодня"
//someDate is berofe than today
} else if dateIter1 == oneDaysAgo1 {
//someDate is equal or after than today
cell.dateLabel.text = "Вчера"
} else {
cell.dateLabel.text = myFeed.objectAtIndex(indexPath.row).objectForKey("Date_text") as? String
}
return cell
}