I am using the code to create borders for my labels here:
extension CALayer {
func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer()
switch edge {
case UIRectEdge.top:
border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: thickness)
break
case UIRectEdge.bottom:
border.frame = CGRect(x: 0, y: self.frame.height - thickness, width: self.frame.width, height: thickness)
break
case UIRectEdge.left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.frame.height)
break
case UIRectEdge.right:
border.frame = CGRect(x: self.frame.width - thickness, y: 0, width: thickness, height: self.frame.height)
break
default:
break
}
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
}
However, when I add this to my layers this is what I get: as you can see, the width is totally messed up and the frame.width is inaccurate.
Im not sure why this could be. I don't set the width in my storyboard because I want the label to work for all phone widths.
Thanks for the help in advance!
A CALayer
doesn't automatically resize when its corresponding UIView
does. You need to override layoutSubviews
in the UIView
and update your borders widths/heights
override func layoutSubviews() {
super.layoutSubviews()
...resize layer or redraw borders here...
}
You could make a BorderedLabel
subclass of UILabel
that handled all this logic for you.
EDIT
If you don't want to deal with creating a subclass of UITableViewCell
and adding your own BorderedLabel
views, you may just need to force the layout before setting the border.
I'm just guessing, since you haven't shared any code, but if you are calling label.text="4517 Bedford..."
and then label.layer.addBorder()
all you need to do is call layoutIfNeeded()
to trigger a layout pass before you addBorder
method measures the frame size.
cell.label.text = "4517 Bedford..."
cell.layoutIfNeeded()
cell.label.layer.addBorder(...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.