Skip to content

Instantly share code, notes, and snippets.

@evgeniyd
Last active August 29, 2015 14:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save evgeniyd/fa36b6f586a5850bca3f to your computer and use it in GitHub Desktop.
UITableViewCell subclass where each cell could have its own separator w/ many styles (currently only .None and .Default are supported). Note: UITableView object's separator style should be set to "None".
import UIKit
enum MPSTableViewCellSeparator {
case Default, None
// returns views for each style - very convinient
func view() -> UIView? {
switch (self) {
case .None:
return nil
default:
let sv = UIView()
sv.backgroundColor = UIColor.lightGrayColor()
sv.alpha = 0.5
return sv
}
}
}
// Note: before get this final solution I've gone through several other
// in the end I recognized, the scruct is not necessary to have
// It is enough to have just 'var currentSeparatorView: UIView?' property
// the current separator type could be taken from respective property
struct MPSSeparator {
var view: UIView?
var type: MPSTableViewCellSeparator
}
class MPSTableViewCell: UITableViewCell {
var separatorType: MPSTableViewCellSeparator {
didSet {
currentSeparatorData?.view?.removeFromSuperview()
currentSeparatorData = nil
currentSeparatorData = MPSSeparator(view: separatorType.view(), type: separatorType)
if let sv = currentSeparatorData!.view {
sv.setTranslatesAutoresizingMaskIntoConstraints( false )
self.addSubview(sv)
}
}
}
private var currentSeparatorData: MPSSeparator?
required init(coder aDecoder: NSCoder) {
separatorType = .None
super.init(coder: aDecoder)
}
override func updateConstraints() {
super.updateConstraints()
switch (separatorType) {
case .None:
0 // Swift, leave me alone here, plz. Just compile this! OK?!
default:
let views = ["separatorView":currentSeparatorData!.view!]
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(5)-[separatorView]|", options: .allZeros, metrics: nil, views: views))
let bottomSpaceConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: currentSeparatorData!.view!, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0)
self.addConstraint(bottomSpaceConstraint)
let heightConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[separatorView(==0.5)]", options: .allZeros, metrics: nil, views: views)
currentSeparatorData!.view!.addConstraints(heightConstraints)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment