I am using a custom UICollectionViewFlowLayout class to achieve multi-scroll behaviour of scroll view. No problem in that.
But to make custom selection and deselection, I need to use custom code inside shouldSelectItemAt function for proper selection/deselection.
Here is the code for it:
Inside MyCustomCollectionViewController:
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if(collectionView == customContentCollectionView){
let cell:MyContentCell = collectionView.cellForItem(at: indexPath)! as! MyCollectionViewController.MyContentCell
if(self.bubbleArray[indexPath.section][indexPath.item].umid != ""){
// DESELECTION LOGIC
if(previouslySelectedIndex != nil){
let (bubbleBorder, bubbleFill) = getBubbleColor(selected: false)
// following line is error prone (executes but may or may not fetch the cell, sometimes deselect sometimes doesn't)
let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell
prevCell?.shapeLayer.strokeColor = bubbleBorder.cgColor
prevCell?.shapeLayer.fillColor = bubbleFill.cgColor
prevCell?.shapeLayer.shadowOpacity = 0.0
prevCell?.labelCount.textColor = bubbleBorder
}
previouslySelectedIndex = []
previouslySelectedIndex = indexPath
// SELECTION LOGIC
if(self.bubbleArray[indexPath.section][indexPath.item].interactions != ""){
let (bubbleBorder, bubbleFill) = getBubbleColor(selected: true)
cell.shapeLayer.strokeColor = bubbleBorder.cgColor
cell.shapeLayer.fillColor = bubbleFill.cgColor
cell.shapeLayer.shadowOffset = CGSize(width: 0, height: 2)
cell.shapeLayer.shadowOpacity = 8
cell.shapeLayer.shadowRadius = 2.0
cell.labelCount.textColor = UIColor.white
}
}
return false
}
return true
}
The code for MyContentCell:
class MyContentCell: UICollectionViewCell{ // CODE TO CREATE CUSTOM CELLS
var gradient = CAGradientLayer()
var shapeLayer = CAShapeLayer()
var horizontalLine = UIView()
var verticalLeftLine = UIView()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
let labelCount: UILabel = {
let myLabel = UILabel()
return myLabel
}()
func setup(){ // initializing cell components here as well as later in cellForItemAt method
............
}
override func prepareForReuse() {
self.shapeLayer.fillColor = UIColor.white.cgColor
self.shapeLayer.shadowOpacity = 0.0
}
}
May be the problem is, when a cell is selected and just dragged out of screen, its perhaps might not being destroyed, that's why the prepare for reuse function is not tracking it to make the deselection. So kindly tell me how to deselect a cell which is just gone outside the screen (visible index)?
You need to invalidate layout
collectionView?.collectionViewLayout.invalidateLayout()
Related
I realize that many people have asked this question in various forms and the answers are all over the page, so let me summarize my specific situation in hopes of getting more specific answers. First of all, I'm building for iOS 11+ and have a relatively recent version of XCode (11+). Maybe not the latest, but recent enough.
Basically, I need a self-sizing tableview where the cells may expand and collapse at runtime when the user interacts with them. In viewDidLoad I set the rowHeight to UITableView.automaticDimension and estimatedRowHeight to some number that's bigger than the canned value of 44. But the cell is not expanding like it should, even though I seem to have tried every bit of advice in the book.
If that matters, I have a custom class for the table cell but no .XIB file for it - the UI is defined directly in the prototype. I've tried a number of other variations, but it feels like the easiest is making a UIStackView the only direct child of the prototype (the "revenue" features so to speak would all be inside it. In my case, they include a label and another tableview - I nest 3 levels deep - but that's probably beside the point) and constraining all 4 of it's edges to the parent. I've tried that, and I've tinkered with the distribution in the stack view (Fill, Fill Evenly, Fill Proportionately), but none of it seems to work. What can I do to make the cells expand properly?
In case anyone's wondering, I used to override heightForRowAt but now I don't because it's not easy to predict the height at runtime and I'm hoping the process could be automated.
Start with the basics...
Here is a vertical UIStackView with two labels:
The red outline shows the frame of the stack view.
If we tap the button, it will set bottomLabel.isHidden = true:
Notice that in addition to being hidden, the stack view removes the space it was occupying.
Now, we can do that with a stack view in a table view cell to get expand/collapse functionality.
We'll start with every-other row expanded:
Now we tap the "Collapse" button for row 1 and we get:
Not quite what we want. We successfully "collapsed" the cell content, but the table view doesn't know anything about it.
So, we can add a closure... when we tap the button, the code in the cell will show/hide the bottom label AND it will use the closure to tell the table view what happened. Our cellForRowAt func looks like this:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "c", for: indexPath) as! ExpColCell
c.setData("Top \(indexPath.row)", str2: "Bottom \(indexPath.row)\n2\n3\n4\n5", isCollapsed: isCollapsedArray[indexPath.row])
c.didChangeHeight = { [weak self] isCollapsed in
guard let self = self else { return }
// update our data source
self.isCollapsedArray[indexPath.row] = isCollapsed
// tell the tableView to re-run its layout
self.tableView.performBatchUpdates(nil, completion: nil)
}
return c
}
and we get:
Here's a complete example:
Simple "dashed outline view"
class DashedOutlineView: UIView {
#IBInspectable var dashColor: UIColor = .red
var shapeLayer: CAShapeLayer!
override class var layerClass: AnyClass {
return CAShapeLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
shapeLayer = self.layer as? CAShapeLayer
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 1.0
shapeLayer.lineDashPattern = [8,8]
}
override func layoutSubviews() {
super.layoutSubviews()
shapeLayer.strokeColor = dashColor.cgColor
shapeLayer.path = UIBezierPath(rect: bounds).cgPath
}
}
The cell class
class ExpColCell: UITableViewCell {
public var didChangeHeight: ((Bool) -> ())?
private let stack = UIStackView()
private let topLabel = UILabel()
private let botLabel = UILabel()
private let toggleButton = UIButton()
private let outlineView = DashedOutlineView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
// button properties
toggleButton.translatesAutoresizingMaskIntoConstraints = false
toggleButton.backgroundColor = .systemBlue
toggleButton.setTitleColor(.white, for: .normal)
toggleButton.setTitleColor(.gray, for: .highlighted)
toggleButton.setTitle("Collapse", for: [])
// label properties
topLabel.text = "Top Label"
botLabel.text = "Bottom Label"
topLabel.font = .systemFont(ofSize: 32.0)
botLabel.font = .italicSystemFont(ofSize: 24.0)
topLabel.backgroundColor = .green
botLabel.backgroundColor = .systemTeal
botLabel.numberOfLines = 0
// outline view properties
outlineView.translatesAutoresizingMaskIntoConstraints = false
// stack view properties
stack.translatesAutoresizingMaskIntoConstraints = false
stack.axis = .vertical
stack.spacing = 8
// add the labels
stack.addArrangedSubview(topLabel)
stack.addArrangedSubview(botLabel)
// add outlineView, stack view and button to contentView
contentView.addSubview(outlineView)
contentView.addSubview(stack)
contentView.addSubview(toggleButton)
// we'll use the margin guide
let g = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
stack.topAnchor.constraint(equalTo: g.topAnchor),
stack.leadingAnchor.constraint(equalTo: g.leadingAnchor),
outlineView.topAnchor.constraint(equalTo: stack.topAnchor),
outlineView.leadingAnchor.constraint(equalTo: stack.leadingAnchor),
outlineView.trailingAnchor.constraint(equalTo: stack.trailingAnchor),
outlineView.bottomAnchor.constraint(equalTo: stack.bottomAnchor),
toggleButton.topAnchor.constraint(equalTo: g.topAnchor),
toggleButton.trailingAnchor.constraint(equalTo: g.trailingAnchor),
toggleButton.leadingAnchor.constraint(equalTo: stack.trailingAnchor, constant: 16.0),
toggleButton.widthAnchor.constraint(equalToConstant: 92.0),
])
// we set the bottomAnchor constraint like this to avoid intermediary auto-layout warnings
let c = stack.bottomAnchor.constraint(equalTo: g.bottomAnchor)
c.priority = UILayoutPriority(rawValue: 999)
c.isActive = true
// set label Hugging and Compression to prevent them from squeezing/stretching
topLabel.setContentHuggingPriority(.required, for: .vertical)
topLabel.setContentCompressionResistancePriority(.required, for: .vertical)
botLabel.setContentHuggingPriority(.required, for: .vertical)
botLabel.setContentCompressionResistancePriority(.required, for: .vertical)
contentView.clipsToBounds = true
toggleButton.addTarget(self, action: #selector(toggleButtonTapped), for: .touchUpInside)
}
func setData(_ str1: String, str2: String, isCollapsed: Bool) -> Void {
topLabel.text = str1
botLabel.text = str2
botLabel.isHidden = isCollapsed
updateButtonTitle()
}
func updateButtonTitle() -> Void {
let t = botLabel.isHidden ? "Expand" : "Collapse"
toggleButton.setTitle(t, for: [])
}
#objc func toggleButtonTapped() -> Void {
botLabel.isHidden.toggle()
updateButtonTitle()
// comment / un-comment this line to see the difference
didChangeHeight?(botLabel.isHidden)
}
}
and a table view controller to demonstrate
class ExpColTableViewController: UITableViewController {
var isCollapsedArray: [Bool] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(ExpColCell.self, forCellReuseIdentifier: "c")
// 16 "rows" start with every-other row collapsed
for i in 0..<15 {
isCollapsedArray.append(i % 2 == 0)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return isCollapsedArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "c", for: indexPath) as! ExpColCell
c.setData("Top \(indexPath.row)", str2: "Bottom \(indexPath.row)\n2\n3\n4\n5", isCollapsed: isCollapsedArray[indexPath.row])
c.didChangeHeight = { [weak self] isCollapsed in
guard let self = self else { return }
// update our data source
self.isCollapsedArray[indexPath.row] = isCollapsed
// tell the tableView to re-run its layout
self.tableView.performBatchUpdates(nil, completion: nil)
}
return c
}
}
I have a following setup:
UploadedCell
DisplayUploadsVC
UploadHelper with delegate that tracks
progress (this is singleton)
In my controller I have a timer in cellForItemAt that gets the progress for uploadId that is currently uploading and update the cell upload item.
In my cell I use prepareForReuse and set my upload to nil.
But again when I scroll and cells reuse I see duplicate cells. I also see when I pullToRefress or go to the end of results to get more results from server.
Just not sure what I'm missing or if I can use this kind of implementation with timer in collection view cell to get the progress.
UploadedCell
class UploadedCell: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
// MARK: Variables declaration
let uploadBadge = UIImageView(image: #imageLiteral(resourceName: "uploads") , contentMode: .scaleAspectFit)
let uploadName = UILabel(font: UIFont.openSansSemiboldFontOfSize(18))
let statusName = UILabel(font: UIFont.openSansSemiboldFontOfSize(18))
#objc lazy var moreButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "dots-menu")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .lightGray
button.addTarget(self, action: #selector(handleMore), for: .touchDown)
return button
}()
// MARK - didSet
var upload: UploadModel.UploadItem? {
didSet {
uploadName.text = upload?.title
statusName.text = upload?.status
}
}
// MARK: - Main Init
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
setupViews()
}
override func prepareForReuse() {
self.upload = nil
super.prepareForReuse()
}
}
DisplayUploadsVC
class DisplayUploadsVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {
// MARK: - Properties
/// various object init
var uploadCell: UploadCell = UploadCell()
var uploadProgress = (progress: Float(0), uploadId: "")
var progressTimer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
UploadHelper.shared.uploadHelperDelegate = self
setupViews()
setupEmptyBackgroundView()
fetchUploads()
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! UploadCell
cell.upload = nil
var upload = isSearching ? filteredResults[indexPath.item] : results?[indexPath.item]
cell.upload = upload
// get uploads with paging if we are paginating
if (self.uploadProgress.uploadId == upload?.id && self.uploadProgress.progress < 99) {
progressTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
upload?.status = String(format: NSLocalizedString("Uploading %.0f%%", comment: ""), self.uploadProgress.progress)
cell.upload = upload
if self.uploadProgress.progress > 99.9 {
self.progressTimer.invalidate()
upload?.status = NSLocalizedString("Upload DONE", comment: "")
cell.upload = upload
}
}
}
return cell
}
extension DisplayUploadsVC : UploadHelperProgress {
func showProgress(progress: Float, uploadId: String) {
self.uploadProgress.progress = progress
self.uploadProgress.uploadId = uploadId
}
}
UploadHelper
protocol UploadHelperProgress : class {
func showProgress(progress: Float, uploadId: String)
}
private var id: String?
private let progressBlock = { bytesWritten, bytesTotal in
var progress = Float(bytesWritten) / Float(bytesTotal)
UploadHelper.shared.uploadHelperDelegate?.showProgress(progress: progress * 100, uploadId: id ?? "")
} as UploadProgressBlock
class UploadHelper: NSObject {
/// delegate
weak var uploadHelperDelegate: UploadHelperProgress?
/// singleton
static let shared = UploadHelper()
func upload(fileUrl: URL, fileUploadUrl: String, uploadId: String) {
id = uploadId
//
// upload logic
//
upload?.progressBlock = progressBlock
upload?.resume()
}
}
I have a paging UIScrollView, each page being populated with a different view controller. Above the scrollview is a UICollectionView that acts as a menu bar. As you scroll through the scrollview pages, the menu bar moves just a little bit. You can see from the gif on the left.
Setting their delegates to different classes keeps everything working correctly as seen in the gif on the left. BUT, setting them to the same class messes up the UICollectionViews behavior.
How do I set their delegates to the same class?
import UIKit
class MenuView: UIView, UICollectionViewDataSource {
let collcetionView: UICollectionView = {
let view = UICollectionView()
// Setup...
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupCollectionView()
collcetionView.dataSource = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupCollectionView() {
// Autolayout code...
}
// Datasource methods to populate collection view cells
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// Populate cell code...
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// Populate cell code...
}
}
class MainView: UIView {
// Contains paging scroll view and menu bar
var menu: MenuView!
let scrollView: UIScrollView = {
let view = UIScrollView()
// Setup...
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupMenu()
setupScrollView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupScrollView() {
// Autolayout code...
}
fileprivate func setupMenu() {
menu = MenuView()
// Autolayout code...
}
}
class MainController: UIViewController, UIScrollViewDelegate, UICollectionViewDelegate {
var mainView: MainView!
override func loadView() {
super.loadView()
mainView = MainView()
view = mainView
}
override func viewDidLoad() {
super.viewDidLoad()
mainView.scrollView.delegate = self
mainView.menu.collcetionView.delegate = self // <<--- THIS IS WHAT BREAKS EVERYTHING
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// Moving menu bar with page scroll
mainView.menu.collectionView.contentOffset = CGPoint(x: scrollView.contentOffset.x/SCROLL_FACTOR - (firstIndexPosition/SCROLL_FACTOR - difference/2), y: 0)
// Fade in and out highlighted state of menu bar cell
let exactPage = (scrollView.contentOffset.x / SCREEN_WIDTH)
let currentPage = (scrollView.contentOffset.x / SCREEN_WIDTH).rounded()
let unitExact = currentPage - exactPage
//print(String(format: "exact: %.2f, ", exactPage) + "current: \(currentPage), " + String(format: "unit: %.2f, ", unitExact))
if exactPage > currentPage {
// exact > current
// fade out/in left icon
// select current
let unit = 0 - unitExact // from 0 - 0.5
let cell = mainView.menu.collectionView.cellForItem(at: IndexPath(item: Int(currentPage), section: 0)) as! MenuBarCell
let mapped = unit.map(from: 0.0...0.5, to: 0...149.0)
print(cell)
setCellColor(cell: cell, value: mapped)
} else if exactPage < currentPage {
// exact < current
// fade out/in right icon
// select current
let unit = unitExact // from 0 - 0.5
let cell = mainView.menu.collectionView.cellForItem(at: IndexPath(item: Int(currentPage), section: 0)) as! MenuBarCell
let mapped = unit.map(from: 0.0...0.5, to: 0...149.0)
setCellColor(cell: cell, value: mapped)
} else if exactPage == currentPage {
// exact = current
// darken that icon
// select current
}
}
}
UICollectionView and UITableView inherit from UIScrollView,
The scrollViewDidScroll delegate method will be called for both your collection view and your scrollview if you set the delegate for both objects to the same class.
You need to check why scrollViewDidScroll is being called and act accordingly.
The simplest approach is a guard statement that returns if the delegate method isn't called for the scroll view you are interested in.
If you needed to execute different code depending on the scroll view involved you could use a series of if statements or a switch statement.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard scrollView == self.scrollView else {
return
}
// Moving menu bar with page scroll
mainView.menu.collectionView.contentOffset = CGPoint(x: scrollView.contentOffset.x/SCROLL_FACTOR - (firstIndexPosition/SCROLL_FACTOR - difference/2), y: 0)
// Fade in and out highlighted state of menu bar cell
let exactPage = (scrollView.contentOffset.x / SCREEN_WIDTH)
let currentPage = (scrollView.contentOffset.x / SCREEN_WIDTH).rounded()
let unitExact = currentPage - exactPage
//print(String(format: "exact: %.2f, ", exactPage) + "current: \(currentPage), " + String(format: "unit: %.2f, ", unitExact))
if exactPage > currentPage {
// exact > current
// fade out/in left icon
// select current
let unit = 0 - unitExact // from 0 - 0.5
let cell = mainView.menu.collectionView.cellForItem(at: IndexPath(item: Int(currentPage), section: 0)) as! MenuBarCell
let mapped = unit.map(from: 0.0...0.5, to: 0...149.0)
print(cell)
setCellColor(cell: cell, value: mapped)
} else if exactPage < currentPage {
// exact < current
// fade out/in right icon
// select current
let unit = unitExact // from 0 - 0.5
let cell = mainView.menu.collectionView.cellForItem(at: IndexPath(item: Int(currentPage), section: 0)) as! MenuBarCell
let mapped = unit.map(from: 0.0...0.5, to: 0...149.0)
setCellColor(cell: cell, value: mapped)
} else if exactPage == currentPage {
// exact = current
// darken that icon
// select current
}
}
I want in UITableViewCell add customized UIView (will be analog segmented control)
I wrote subclass `protocol ITISegmentedViewDelegate: class {
func segmentedViewButtonChanged(index: Int)
}
public protocol ITISegmentedViewDataSource : NSObjectProtocol {
#available(iOS 2.0, *)
func segmentedView(itemsInSegmentedView: ITISegmentedView) -> [String]
}
public class ITISegmentedView: UIView {
var delegate: ITISegmentedViewDelegate?
var dataSource: ITISegmentedViewDataSource?
var selectedItem = -1
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.addButtons()
}
private func addButtons(){
if delegate == nil || dataSource == nil{
return
}
let height = frame.height
let width = frame.width
let array = dataSource!.segmentedView(self)
let totalItem = array.count
var startX = CGFloat(0)
for var index = 0; index < totalItem; ++index{
let button = UIButton(frame: CGRectMake(startX, 0, width/CGFloat(totalItem), height))
button.setTitle(array[index], forState: UIControlState.Normal)
button.tag = index
button.addTarget(button, action: "onButtonPressed", forControlEvents: .TouchUpInside)
startX += width/CGFloat(totalItem)
addSubview(button)
}
if totalItem>0{
selectedItem = 0
delegate?.segmentedViewButtonChanged(0)
}
}
func onButtonPressed(button: UIButton){
if selectedItem != button.tag{
delegate?.segmentedViewButtonChanged(button.tag)
selectedItem = button.tag
}
}
}`
In storyboard added UIView and set class ITISegmentedView
in my ViewController:
let cell = tableView.dequeueReusableCellWithIdentifier( cellName, forIndexPath: indexPath)
let seg = (cell.viewWithTag(1) as! ITISegmentedView)
seg.dataSource = self
seg.delegate = self
PROBLEM:
init(coder aDecoder: NSCoder) calls on dequeueReusableCell and at this moment data source and delegate is not set, so ITISegmentedView doesn't work.
Fall back to an empty dataSource when you encounter nil.
Also, try not to use !, but rather ? and ?? to always take into account that an Optional is... well. Optional.
I'm using MGSwipeTableCell in swift, but have tried multiple other libraries, all resulting in the same problem.
Basically, I set up a custom cell class, of the type MGSwipeTableCell. I add some labels, etc, and this all works well. See code below for Cell Class Code.
import UIKit
import BTLabel
import MGSwipeTableCell
class MessageCell: MGSwipeTableCell {
let name = UILabel()
let contactTime = BTLabel()
let lineSeperator = UIView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override func layoutSubviews() {
super.layoutSubviews()
self.backgroundColor = Styles().heyGreen()
self.selectionStyle = .None
name.frame = CGRectMake(self.bounds.width/10, self.bounds.height/5, self.bounds.width/10*7, self.bounds.height/10*5)
name.backgroundColor = UIColor.clearColor()
name.font = Styles().FontBold(30)
name.textColor = UIColor.whiteColor()
name.textAlignment = .Left
self.addSubview(name)
contactTime.frame = CGRectMake(self.bounds.width/10, self.bounds.height/10*7, self.bounds.width/10*7, self.bounds.height/10*2)
contactTime.backgroundColor = UIColor.clearColor()
contactTime.font = Styles().FontBold(15)
contactTime.textColor = Styles().heySelectedOverLay()
contactTime.verticalAlignment = .Top
contactTime.textAlignment = .Left
self.addSubview(contactTime)
lineSeperator.frame = CGRectMake(0, self.bounds.height - 1, self.bounds.width, 1)
lineSeperator.backgroundColor = Styles().heySelectedOverLay()
self.addSubview(lineSeperator)
}
}
The cellForRowMethod is as follows in my tableviewcontroller.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdendifier: String = "MessageCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdendifier) as! MessageCell!
if cell == nil {
tableView.registerClass(MessageCell.classForCoder(), forCellReuseIdentifier: cellIdendifier)
cell = MessageCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdendifier)
}
cell.name.text = "heysup"
cell.contactTime.text = "100 days"
cell.delegate = self //optional
//configure left buttons
cell.leftButtons = [MGSwipeButton(title: "", icon: UIImage(named:"check.png"), backgroundColor: UIColor.greenColor())
,MGSwipeButton(title: "", icon: UIImage(named:"fav.png"), backgroundColor: UIColor.blueColor())]
cell.leftSwipeSettings.transition = MGSwipeTransition.Rotate3D
//configure right buttons
cell.rightButtons = [MGSwipeButton(title: "Delete", backgroundColor: UIColor.redColor())
,MGSwipeButton(title: "More",backgroundColor: UIColor.lightGrayColor())]
cell.rightSwipeSettings.transition = MGSwipeTransition.Rotate3D
return cell
}
The problem lies in that this is how it looks when i swipe across.
I'm not sure where it's going wrong or what it's doing. I'm also not sure if it's because i'm adding the labels to the wrong layer? I remember in obj-c you used to add things to the cell view or something to that effect...
Any advice?
I actually resolved this issue - i needed to add the labels to the contentView, not the actual view.
so the code should have been
self.contentView.addSubview(name)
for example, on the custom tableviewcell