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".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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