iOS: prettify random color for debugging
I used to use random color to debug, from colors I like
extension CALayer{
func debug(){
let colors = [UIColor.blue, UIColor.magenta, UIColor.red,
UIColor.green, UIColor.brown, UIColor.purple,
UIColor.cyan]
if let color = colors.randomElement().cgColor{
borderColor = color
}
}
}
The effect case:
The colors are not of regularity. Not very pretty.
I want to prettify it. Do some color alignment. The same color for the same UI hierarchy.
achieve something like this.
In order to not make colors repeat, and to show more colors in a page. I use ring buffer.
In order to do some color alignment, the same color for the same UI hierarchy,I use call stack trace. Use the call function as the key for its color.
Here is the code:
// the color ring buffer
struct ColorCluster {
static var shared = ColorCluster()
let colors = [UIColor.blue, UIColor.magenta, UIColor.red,
UIColor.green, UIColor.brown, UIColor.purple,
UIColor.cyan]
var colorRegister = [String: Int]()
var count = -1
mutating func get(_ k: String) -> CGColor{
var index = 0
if let idx = colorRegister[k]{
index = idx
}
else{
count += 1
if count >= colors.count{
count = 0
}
index = count
colorRegister[k] = count
}
return colors[index].cgColor
}
}
extension CALayer{
func debug(){
// call stack trace, remove methods of the system
let libs: Set<String> = ["UIKitCore", "QuartzCore", "CoreFoundation"]
var methods = [String]()
Out: for symbol in Thread.callStackSymbols{
for lib in libs {
if symbol.contains(lib){
break Out
}
}
methods.append(symbol)
}
var edgeColor = UIColor.black.cgColor // color place holder
if let name = methods.last{
edgeColor = ColorCluster.shared.get(name)
}
borderColor = edgeColor
borderWidth = 1
}
}
Usage:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(for: PracticeDetailCell.self, ip: indexPath)
cell.layer.debug()
return cell
}