Okay, so I am trying to add a button to a table view cell. My table view cell has an image, label and a button. I set the button to be hidden in storyboard. Now I'm trying to show the button if the label text is truncated, I set the number of lines on my label to 3 in storyboard. It works but when I scroll up and down, somehow some cells with the label text not truncated shows a button. Why?
This is how my cell file looks atm.
class ItemCell: UITableViewCell {
#IBOutlet weak var itemImageView: UIImageView!
#IBOutlet weak var itemTitleLabel: UILabel!
#IBOutlet weak var itemDetailLabel: UILabel!
#IBOutlet weak var moreButton: UIButton!
var item: Item? {
didSet {
configureCell()
}
}
private func configureCell() {
guard let item = item else { return }
itemImageView.image = item.image
itemTitleLabel.text = item.name
itemDetailLabel.text = item.description
if itemDetailLabel.isTruncated {
moreButton.isHidden = false
} else {
moreButton.isHidden = true
}
}
extension UILabel {
var isTruncated: Bool {
guard let labelText = text else {
return false
}
let labelTextSize = (labelText as NSString).boundingRect(
with: CGSize(width: frame.size.width, height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [.font: font],
context: nil).size
return labelTextSize.height > bounds.size.height
}
}
This is how my cellForRowAt looks like.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as? ItemCell else {
return UITableViewCell()
}
let item = categories[indexPath.section].items[indexPath.row]
cell.item = item
print("Name: \(item.name)\nSection: \(indexPath.section)\nRow: \(indexPath.row)\nisTruncated: \(cell.itemDetailLabel.isTruncated)\n")
return cell
}
Related
I am trying to display table view cell property into different table view cell when button I clicked . I am using story board . I added the Horizontal and vertical stack to contains the image and label properties . I want to display this property into another table view cell when user clicked the show button . In cellFor row function i defined the button action property . I am getting following error .Class 'DetailsViewCell' has no initializers. Cannot use instance member 'mc' within property initializer; property initializers run before 'self' is available
Here is the screenshot of the both view controller .
Here is the code .
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// guard let cell = tableView.dequeueReusableCell(withIdentifier: MovieCell.identifier, for: indexPath) as? MovieCell
// else { return UITableViewCell() }
let cell = tableView.dequeueReusableCell(withIdentifier: MovieViewCell.identifier, for: indexPath) as! MovieViewCell
cell.showButton.tag = indexPath.row
cell.showButton.addTarget(self, action: Selector("movieDetails"), for: .touchUpInside)
let row = indexPath.row
let title = presenter.getTitle(by: row)
let overview = presenter.getOverview(by: row)
let data = presenter.getImageData(by: row)
cell.configureCell(title: title, overview: overview, data: data)
return cell
}
}
Here is the code in identifier class with table view cell.
class MovieViewCell: UITableViewCell {
static let identifier = "MovieViewCell"
#IBOutlet weak var mainStackView: UIStackView!
#IBOutlet weak var movieImage: UIImageView!
#IBOutlet weak var movieTtile: UILabel!
#IBOutlet weak var movieOverview: UILabel!
#IBOutlet weak var showButton: UIButton!
#IBAction func movieDetails(_ sender: UIButton) {
var dc : DetailsViewCell
movieTtile = dc.movieTitle
movieOverview = dc.movieOverview
movieImage = dc.movieImage
}
func configureCell(title: String?, overview: String?, data: Data?) {
movieTtile.text = title
movieOverview.text = overview
if let imageData = data{
movieImage.image = UIImage(data: imageData)
}
}
}
Here is the code for Details view cell.
class DetailsViewCell: UITableViewCell {
#IBOutlet weak var movieTitle: UILabel!
#IBOutlet weak var movieOverview: UILabel!
#IBOutlet weak var movieImage: UIImageView!
var mc : MovieViewCell
movieTitle = mc.movieTtile
movieOverview = mc.movieOverview
movieImage = mc.movieImage
}
import UIKit
var loginData = ["", "", ""]
class LoginDataCell: UITableViewCell, UITextFieldDelegate {
#IBOutlet weak var txtLoginData: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.tag == 0 {
loginData[0] = textField.text
} else if textField.tag == 1 {
loginData[1] = textField.text
} else if textField.tag == 2 {
loginData[2] = textField.text
}
}
}
As below gif showed, in the specific row of tableView, the playing song's image(Just Dance.mp3) is changed to dynamic image.
My main question is how to achieve this effect in my App, to use a GIF image or other approach? Need advice here.
What effect I want to achieve:
when a song is playing, the specific row cell's image is changed to dynamic image. (the main question)
if the song is paused, then that dynamic image stop to play.
when another song is selected to play, the previous song's(cell) image is resume to its album artwork.
Here is my snip code, I'm not test it yet since I'm not sure if I should use GIF or other approach.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
if resultSearchController.isActive {
cell.addButton.tag = indexPath.row
cell.songTitle.text = filteredTableData[indexPath.row].songName
cell.songArtist.text = filteredTableData[indexPath.row].artistName
cell.songArtwork.image = filteredTableData[indexPath.row].albumArtwork
return cell
} else {
cell.addButton.tag = indexPath.row
cell.songTitle.text = tableData[indexPath.row].songName
cell.songArtist.text = tableData[indexPath.row].artistName
cell.songArtwork.image = tableData[indexPath.row].albumArtwork
return cell
}
// set image of specific tableView row cell to GIF image
if indexPath.row == SongData.currentTrack {
let image = UIImage(named: "playing-gif-image")
cell.songArtwork.image = image
} else {
// do nothing
}
}
===================================================================
Update my code according to ATV's answer, currently I use static image to set different state of playing cell. Well I get interested to this fancy CAShapeLayer:), and I need time to learn about it then to set the dynamic image for the specific cell.
/ / / Model, SongData.swift
import UIKit
class SongData: NSObject, NSCoding {
var songName: String
var artistName: String
var albumName: String
var albumArtwork: UIImage
var url: URL
static var songList = [SongData]()
static var shuffleSongList = [SongData]()
static var currentTrack = 0
static var showCurrentPlayingSong = false
static var repeatSequence = "repeatList"
static var isPlaying = false
enum PlayingCellState {
case nonState
case playing
case paused
}
init(songName: String, artistName: String, albumName: String, albumArtwork: UIImage, url: URL) {
self.songName = songName
self.artistName = artistName
self.albumName = albumName
self.albumArtwork = albumArtwork
self.url = url
}
...
}
/ / / CustomCell.swift
import UIKit
class CustomCell: UITableViewCell {
#IBOutlet weak var songTitle: UILabel!
#IBOutlet weak var songArtist: UILabel!
#IBOutlet weak var songArtwork: UIImageView!
#IBOutlet weak var addButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
songArtwork.layer.cornerRadius = 8.0
}
func config(forState state: SongData.PlayingCellState) {
// setup your cell depends on state
switch state {
case .nonState:
print("nonState") //update cell to default state
case .playing:
songArtwork.image = UIImage(named: "Play")
case .paused:
songArtwork.image = UIImage(named: "Pause")
}
}
}
/ / / TableViewController
// use for track cell state, for playing dynamic image usage
func stateForCell(at indexPath: IndexPath) -> SongData.PlayingCellState {
// when firstly open the tab song list/app(with no song played), do not attach playing state image
if SongData.songList.count == 0 {
return .nonState
} else {
if indexPath.row == SongData.currentTrack {
return SongData.isPlaying ? .playing : .paused
} else {
return .nonState
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
if resultSearchController.isActive {
cell.addButton.tag = indexPath.row
cell.songTitle.text = filteredTableData[indexPath.row].songName
cell.songArtist.text = filteredTableData[indexPath.row].artistName
cell.songArtwork.image = filteredTableData[indexPath.row].albumArtwork
// return cell
} else {
cell.addButton.tag = indexPath.row
cell.songTitle.text = tableData[indexPath.row].songName
cell.songArtist.text = tableData[indexPath.row].artistName
cell.songArtwork.image = tableData[indexPath.row].albumArtwork
// return cell
}
cell.config(forState: stateForCell(at: indexPath))
return cell
}
/// Update, finally I make it worked, to involve lottie-ios library, and import it in CustomCell.swift, implement it in playAnimation(), but the pity thing is that animation repeat mode is not working, the animation just repeat once even I set the loopMode. I will search what is wrong later.
import UIKit
import Lottie
class CustomCell: UITableViewCell {
#IBOutlet weak var songTitle: UILabel!
#IBOutlet weak var songArtist: UILabel!
#IBOutlet weak var songArtwork: UIImageView!
#IBOutlet weak var view: UIView!
#IBOutlet weak var addButton: UIButton!
let animationView = AnimationView()
override func awakeFromNib() {
super.awakeFromNib()
songArtwork.layer.cornerRadius = 8.0
}
func playAnimation(){
let animation = Animation.named("366-equalizer-bounce")
animationView.animation = animation
// weird thing is that animation repeat is not working here...
animationView.loopMode = LottieLoopMode.repeat(3600.0)
animationView.play()
animationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(animationView)
NSLayoutConstraint.activate([
animationView.heightAnchor.constraint(equalTo: view.heightAnchor),
animationView.widthAnchor.constraint(equalTo: view.widthAnchor)
])
}
func config(forState state: SongData.PlayingCellState) {
// setup your cell depends on state
switch state {
case .nonState:
print("nonState")
view.isHidden = true
case .playing:
view.isHidden = false
playAnimation()
case .paused:
view.isHidden = false
// to set this latter
// songArtwork.image = UIImage(named: "Pause")
}
}
}
For the implementing of:
"Is that a GIF image used or other dynamic image?" - You can choose any of the options below that is more preferable for you:
You can use GIF image (the similar question)
You can even
draw it by using UIBezierPath and CAShapeLayer (some
examples)
Or use lottie-ios library which can work with Adobe After Effects animations (eg you can use this)
Changing of the cell's state:
//e.g. add it to your presenter or wherever you are storing info about `currentTrack`
...
enum PlayingCellState {
case default
case playing
case paused
...
}
...
func stateForCell(at indexPath: IndexPath) -> PlayingCellState {
if indexPath.row == SongData.currentTrack {
return isPlaying? .playing : .paused
} else {
return .default
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
if resultSearchController.isActive {
cell.addButton.tag = indexPath.row
cell.songTitle.text = filteredTableData[indexPath.row].songName
cell.songArtist.text = filteredTableData[indexPath.row].artistName
cell.songArtwork.image = filteredTableData[indexPath.row].albumArtwork
return cell
} else {
cell.addButton.tag = indexPath.row
cell.songTitle.text = tableData[indexPath.row].songName
cell.songArtist.text = tableData[indexPath.row].artistName
cell.songArtwork.image = tableData[indexPath.row].albumArtwork
return cell
}
cell.config(forState: stateForCell(at: indexPath)
}
//add to your CustomCell
func config(forState state: PlayingCellState) {
// setup your cell depends on state
}
I have collection view of products like the image below
if the product is in stock, the the button will be black, otherwise the button background color will be yellow.
but as you can see from the file gif in here: http://g.recordit.co/HTEVw88Tt4.gif
the first product (index = 0) from the image slider initially has black button (stock is still available), in the array it only has 1 product that out of stock, but after I scroll to right and then back to the first index (index = 0) then suddenly the button become yellow (as if now it has 2 product that out of stock) even though the product that out of stock (yellow button) is only one product.
how to solve this issue?
here is the simplified class of the product:
class Product {
var productID : Int = 0
var name : String = ""
var quantityFromServer: Int = 0
var lowLimit : Int = 0
var isInStock : Bool {
return quantityFromServer > lowLimit ? true : false
}
convenience init(dictionary: [String:Any]) {
self.init()
name = dictionary["products_name"] as? String ?? ""
quantityFromServer = dictionary["products_quantity"] as? Int ?? 0
lowLimit = dictionary["low_limit"] as? Int ?? 0
}
}
in the view controller I set the cellForRow at using the code below
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == firstListProductCollectionView {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeStoryBoardData.CollectionViewIdentifiers.productSliderCell.rawValue, for: indexPath) as! ListProductCell
let selectedProduct = firstProducts[indexPath.item]
cell.minimumOrderQuantity = selectedProduct.minimumOrderQuantity
cell.stepperValue = selectedProduct.quantityInCart
cell.productData = selectedProduct
cell.delegate = self
cell.collectionView = firstListProductCollectionView
cell.indexPath = indexPath
return cell
}
}
and here is the code on my collection view cell
class ListProductCell: UICollectionViewCell {
#IBOutlet weak var addToCartButton: UIButton!
#IBOutlet weak var counterStackView: UIStackView!
#IBOutlet weak var textFieldStepper: UITextField!
#IBOutlet weak var decrementButton: UIButton!
#IBOutlet weak var incrementButton: UIButton!
#IBOutlet weak var loveButtonHeightConstraint: NSLayoutConstraint!
#IBOutlet weak var loveButtonWidthConstraint: NSLayoutConstraint!
var minimumOrderQuantity = 0
var stepperValue = 0
var indexPath: IndexPath?
var collectionView : UICollectionView?
var delegate: ListProductCellDelegate?
var productData : Product? {
didSet {
updateUI()
checkIfProductIsInStock()
}
}
override func awakeFromNib() {
super.awakeFromNib()
setSpecialConstraint()
}
func checkIfProductIsInStock() {
guard let product = productData else {return}
if !product.isInStock {
showAddToCartButton(status: true)
addToCartButton.isEnabled = false
addToCartButton.setTitle("HABIS", for: .normal)
addToCartButton.setTitleColor(.black, for: .normal)
addToCartButton.backgroundColor = AppColor.mainYellow.getUIColor()
}
}
}
I use checkIfProductIsInStock() method in the property observer of productData to check whether to show yellow button or black button.
Cells are dequeued , you need else here
if product.isInStock {
// supply in stock logic here
}
else {
showAddToCartButton(status: true)
addToCartButton.isEnabled = false
addToCartButton.setTitle("HABIS", for: .normal)
addToCartButton.setTitleColor(.black, for: .normal)
addToCartButton.backgroundColor = AppColor.mainYellow.getUIColor()
}
This happens because of the behavior of dequeueing the cells. At this point, I would recommend to override prepareForReuse():
Performs any clean up necessary to prepare the view for use again.
In your custom UICollectionViewCell class, add:
override func prepareForReuse() {
super.prepareForReuse()
// do the reset/cleanup here...
}
I create Scrolling Parallax Effect in Table View Cell in my project but i have some freeze when i scrolling.
My code in custom Table View Cell :
class newsTableViewCell: UITableViewCell {
#IBOutlet weak var imageNews: UIImageView!
#IBOutlet weak var titleLable: UILabel!
#IBOutlet weak var imageHeight: NSLayoutConstraint!
#IBOutlet weak var imageTop: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
imageNews.clipsToBounds = true
}
}
Code in my Main View Controller:
var paralaxOfSetSpeed: CGFloat = 70
var cellHeignt: CGFloat = 170
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! newsTableViewCell
let good = data[indexPath.row]
cell.titleLable.text = (good["title"] as! String)
cell.imageHeight.constant = paralaxImageHeight
cell.imageTop.constant = paralaxOfSet(newOfSetY: tableView.contentOffset.y, cell: cell)
let newsImage = good["image"] as! PFFile
newsImage.getDataInBackground{ (imageData, error) in
if imageData != nil {
let image = UIImage(data: imageData!)
cell.imageNews.image = image
} else {
print(error ?? "getDataInBackground error")
}
}
return cell
}
func paralaxOfSet(newOfSetY: CGFloat, cell: UITableViewCell) -> CGFloat {
return (newOfSetY - cell.frame.origin.y) / paralaxImageHeight * paralaxOfSetSpeed
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let ofSetY = tableView.contentOffset.y
for cell in tableView.visibleCells as! [newsTableViewCell] {
cell.imageTop.constant = paralaxOfSet(newOfSetY: tableView.contentOffset.y, cell: cell)
}
}
var paralaxImageHeight: CGFloat {
let maxOffSet = (sqrt(pow(cellHeignt, 2) + 4 * paralaxOfSetSpeed * self.tableView.frame.height ) - cellHeignt) / 1.5
return maxOffSet + self.cellHeignt
}
This is my code, main problem it's scrolling because it's a not smooth.
UPDATE:
So in the end, i want to get something like this:
I would suggest you to look into the below libraries:
They have implemented the parallax view in TableViewCell
https://github.com/marty-suzuki/SAParallaxViewControllerSwift
Hope it helps.
I put stepper both outlets and action into tableview cell and using protocol delegate to connect it to tableview. When i tapped stepper in first row, stepper value appear normaly in first row but its also appear in some random row. how to fix this?
TableViewCell
protocol ReviewCellDelegate{
func stepperButton(sender: ReviewTableViewCell)
}
class ReviewTableViewCell: UITableViewCell {
#IBOutlet weak var countStepper: UIStepper!
#IBOutlet weak var stepperLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func stepperButtonTapped(sender: UIStepper) {
if delegate != nil {
delegate?.stepperButton(self)
stepperLabel.text = "x \(Int(countStepper.value))"
}
}
ViewController
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "reviewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ReviewTableViewCell
var imageView: UIImageView?
let photoG = self.photos[indexPath.row]
imageView = cell.contentView.viewWithTag(1) as? UIImageView
//let layout = cell.goodiesImage
let tag = indexPath.row // +1
cell.tag = tag
photoG.fetchImageWithSize(CGSize(width: 1000, height: 1000), completeBlock: { image, info in
if cell.tag == tag {
imageView?.image = image
cell.goodiesImage.image = image
}
})
func stepperButton(sender: ReviewTableViewCell) {
if let indexPath = tableView.indexPathForCell(sender){
print(indexPath)
}
}
Reset the value of stepper while loading your cell. you can reset the cell property values in cell's prepareForReuse method. add the following method in your ReviewTableViewCell class.
override func prepareForReuse()
{
super.prepareForReuse()
countStepper.value = 0.0
}
In tableViewCell VC:
1 - add these field
var cellDelegate: cellProtocol?
var index: IndexPath?
2 - then add this in the delegate:
func onStepperClick(index: Int, sender: UIStepper)
3 - when you have dragged your stepper over as an action use this:
#IBAction func cellStepper(_ sender: UIStepper) {
cellDelegate?.onStepperClick(index: (index?.row)!, sender: sender)
sender.maximumValue = 1 //for incrementing
sender.minimumValue = -1 //for decrementing
//this will make sense later
}
In ViewController
1 - add these to the tableView function that has the cellAtRow variable.
cell.cellDelegate = self
cell.index = indexPath
2 - Use this instead of your stepperButton function
func onStepperClick(index: Int, sender: UIStepper) {
print(index)
if sender.value == 1.0{
//positive side of stepper was pressed
}else if sender.value == -1.0{
//negative side of stepper was pressed
}
sender.value = 0 //resetting to zero so sender.value produce different values on plus and minus
}
Hope this works for you
As mentioned by #A-Live, your component is being reused and so need to be updated.
So in your view controller:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "reviewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ReviewTableViewCell
var imageView: UIImageView?
let photoG = self.photos[indexPath.row]
imageView = cell.contentView.viewWithTag(1) as? UIImageView
//let layout = cell.goodiesImage
let tag = indexPath.row // +1
cell.tag = tag
photoG.fetchImageWithSize(CGSize(width: 1000, height: 1000), completeBlock: { image, info in
if cell.tag == tag {
imageView?.image = image
cell.goodiesImage.image = image
}
})
cell.countStepper.value = XXX[indexPath.row].value; //Here you update your view
cell.stepperLabel.text = "x \(Int(cell.countStepper.value))" //And here
And
func stepperButton(sender: ReviewTableViewCell) {
if let indexPath = tableView.indexPathForCell(sender){
print(indexPath)
XXX[sender.tag].value = sender.counterStepper.value //Here you save your updated value
}
NOTE:
1.MY Cell class is just normal..All changes are in viewcontroller class
2.I have taken stepper and over it added ibAddButton with same constraint as ibStepper
class cell: UITableViewCell {
#IBOutlet weak var ibAddButton: UIButton!
#IBOutlet weak var ibStepper: UIStepper!
#IBOutlet weak var ibCount: UILabel!
#IBOutlet weak var ibLbl: UILabel!
}
1.define empty int array [Int]()
var countArray = [Int]()
2.append countArray with all zeros with the number of data u want to populate in tableview
for arr in self.responseArray{
self.countArray.append(0)
}
3.in cell for row at
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! cell
let dict = responseArray[indexPath.row] as? NSDictionary ?? NSDictionary()
cell.ibLbl.text = dict["name"] as? String ?? String()
if countArray[indexPath.row] == 0{
cell.ibAddButton.tag = indexPath.row
cell.ibStepper.isHidden = true
cell.ibAddButton.isHidden = false
cell.ibCount.isHidden = true
cell.ibAddButton.addTarget(self, action: #selector(addPressed(sender:)), for: .touchUpInside)
}else{
cell.ibAddButton.isHidden = true
cell.ibStepper.isHidden = false
cell.ibStepper.tag = indexPath.row
cell.ibCount.isHidden = false
cell.ibCount.text = "\(countArray[indexPath.row])"
cell.ibStepper.addTarget(self, action: #selector(stepperValueChanged(sender:)), for: .valueChanged)}
return cell
}
4.objc functions
#objc func stepperValueChanged(sender : UIStepper){
if sender.stepValue != 0{
countArray[sender.tag] = Int(sender.value)
}
ibTableView.reloadData()
}
#objc func addPressed(sender : UIButton){
countArray[sender.tag] = 1//countArray[sender.tag] + 1
ibTableView.reloadData()
}