TIMEX TIMEX - 7 months ago 33
Swift Question

How do I create a "down caret" on my UITableView separator?

In my UITableView, I am setting my separators like this:

self.tableView.clipsToBounds = true
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
self.tableView.separatorColor = UIColor(hex: 0xededed)
self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
self.tableView.layoutMargins = UIEdgeInsetsZero


And my cells are like this:

override func awakeFromNib() {
super.awakeFromNib()
self.layoutMargins = UIEdgeInsetsZero
self.contentView.layer.borderWidth = 0.0
self.layer.borderWidth = 0.0
}


This allows me to have edge-to-edge separators:

original

I'm trying to create a "down caret" for some of my cells (some cells will have it, some won't). If a cell has it, it will cover the top left portion of the separator, like this:

caret

Notice the caret at the top left of each cell.

What's the best way to achieve this? Maybe use an image and cover the separator? Or should the caret be drawn by code?

Answer

The best solution from a design perspective would be to subclass UITableViewCell (see this question).

As for displaying the down arrow you have a lot of options to get some UIView subclas to display an arrow. I used the unicode character for a down arrow with a UILabel and it works well. You could also use custom drawing code with CoreGraphics, an UIImageView or possibly a some polygonal drawing framework.

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

let downArrowView = UILabel()
downArrowView.text = "\u{25BC}"
downArrowView.sizeToFit()
cell.addSubview(downArrowView)

// Offset to compensate for whitespace around the arrow; adjust to your preference
var frame = downArrowView.frame
frame.origin.y -= 5
frame.origin.x -= 2
downArrowView.frame = frame

Down arrow screenshot

Comments