I am trying to create custom table view cell which works fine in my other UIViewControllers. However, in one of my controllers, the shadow is not growing, I can barely see the shadow.
Here is an image of the shadow being shown in red, you can see it is barely visible.
My cell has a UIView added inside the contentView to creating floating cell effects - the same code and same storyboard layouts are being used across my controllers but this is the only table view where the shadow issue is occurring - so I must be missing something.
My addShadow extension:
extension UIView {
func addShadow(offset: CGSize, color: UIColor, radius: CGFloat, opacity: Float) {
layer.masksToBounds = false
layer.shadowOffset = offset
layer.shadowColor = color.cgColor
layer.shadowRadius = radius
layer.shadowOpacity = opacity
}
}
My awakeFromNib on the custom cell:
:: cellContentView is my UIView added to the base contentView of the cell.
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = .clear
self.selectionStyle = .none
cellContentView?.layer.masksToBounds = true
cellContentView?.round(corners: [.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 10)
cellContentView?.addShadow(offset: CGSize(width: 40, height: 60), color: UIColor.red, radius: 10, opacity: 1)
cellContentView?.layer.shouldRasterize = true
}
Note: The .round is an extension being used on all my cells.
No matter what radius or offset I add for this shadow, it does not get bigger than the image. Also, none of my other cells in the their controllers require the shouldRasterize property to be set, but this does.
Does anyone know what is happening here?
Thanks :)
Edit
Strangely, if I add constraints around my view to keep the gaps large between my view and the cell content view, the background colour disappears - this is set to white in the storyboard.
You should call in the layoutSubviews method. because shadow should add after the view is uploaded
override func awakeFromNib() {
super.awakeFromNib()
//init methods
}
override public func layoutSubviews() {
super.layoutSubviews()
//Added shadow
self.reloadLayers()
}
private func reloadLayers() {
self.layer.cornerRadius = 5
self.addShadow(.TransactionCell)
}
I hope it helps
Content view will fill you cell, so you need to add shadow to view inside content view which has all your components inside it. Then add constraints to it with gap between that view and content view. Second, 40 and 60 properties for shadow is likely too large, when I said too large I mean unbelievable large, because gap between content views in cells are no more than 15 - 30 even less. so try it with much less values, while radius can remain 10 but you will see what value fit the best. If cell content view is your custom view just values will did the job if your view is not kind of transparent or any inside it, in that case it won't, and there is hard to fix that, I tried many libraries and custom codes and it is never ok.
squircleView.layer.cornerRadius = 40
squircleView.layer.cornerCurve = CALayerCornerCurve.continuous
squircleView.layer.shadowColor = UIColor.systemGray.cgColor
squircleView.layer.shadowOpacity = 0.7
squircleView.layer.shadowOffset = CGSize(width: 0, height: 0.5)
squircleView.layer.shadowRadius = 5
Related
Background: My app allows users to select a gradient border to apply to UITableViewCells that are dynamically sized based on the content within them. I am currently creating this border by inserting a CAGradientLayer sublayer to a UIView that sits within the cell.
Issue: Because each cell is sized differently, I am resizing the CAGradientLayer by overriding layoutIfNeeded in my custom cell class. This works, but seems suboptimal because the border is being redrawn over and over again and flickers as the cell is resizing.
Link to Screen Capture:
https://drive.google.com/file/d/1SiuNozyUM7LCdYImZoGCWeoeBKu2Ulcw/view?usp=sharing
Question: Do I need to take a different approach to creating this border? Or am I missing something regarding the UITableViewCell lifecycle? I have come across similar issues on SO, but none that seem to address this redraw issue. Thank you for your help.
CAGradientLayer Extension to Create Border
extension CAGradientLayer {
func createBorder(view: UIView, colors: [CGColor]) {
self.frame = CGRect(origin: CGPoint.zero, size: view.bounds.size)
self.colors = colors
let shape = CAShapeLayer()
shape.lineWidth = 14
shape.path = UIBezierPath(roundedRect: view.bounds, cornerRadius: 12).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
self.mask = shape
}
}
TableViewCell Class - Insert CAGradientLayer
override func awakeFromNib() {
super.awakeFromNib()
reportCard.layer.insertSublayer(gradientLayer, at: 0)
...
}
TableViewCell Class - Resize the Border and Apply User Selected Design
override func layoutIfNeeded() {
super.layoutIfNeeded()
switch currentReport?.frameId {
case "sj_0099_nc_frame_001":
gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.lavender, App.BorderColors.white])
case "sj_0099_nc_frame_002":
gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.red, App.BorderColors.white])
case "sj_0099_nc_frame_003":
gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.yellow, App.BorderColors.white])
default:
gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.white, App.BorderColors.white])
}
}
Turns out I was looking in the wrong place all along. The code in my original post is functional, and updating the gradientLayer frame in layoutIfNeeded() or setNeedsLayout() rather than layoutSubviews() accurately draws the gradientLayer. Per Apple documentation, layoutSubviews() should not be called directly.
The source of the bug was not in my custom cell, but in my tableViewController. I had an extraneous call to reloadData().
Instead of inside awakeFromNib() use this
override func layoutSubviews() {
super.layoutSubviews()
reportCard.layer.insertSublayer(gradientLayer, at: 0)
reportCard.clipsToBounds = true
}
I am trying to set an underline on my UITextFields. I have tried a couple of methods but none of them seem to work. After looking through a couple of websites, the most suggested method is the following:
extension UITextField {
func setUnderLine() {
let border = CALayer()
let width = CGFloat(0.5)
border.borderColor = UIColor.lightGray.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width-10, height: self.frame.size.height)
border.borderWidth = width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}
I can't think of any reason as to why the code above would not work, but all the answers I saw were posted a couple of years ago.
Could someone please let me know what I am doing wrong?
One problem I see with the code that you posted is that it won't update the layer if the text field gets resized. Each time you call the setUnderLine() function, it adds a new layer, then forgets about it.
I would suggest subclassing UITextField instead. That code could look like this:
class UnderlinedTextField: UITextField {
let underlineLayer = CALayer()
/// Size the underline layer and position it as a one point line under the text field.
func setupUnderlineLayer() {
var frame = self.bounds
frame.origin.y = frame.size.height - 1
frame.size.height = 1
underlineLayer.frame = frame
underlineLayer.backgroundColor = UIColor.blue.cgColor
}
// In `init?(coder:)` Add our underlineLayer as a sublayer of the view's main layer
required init?(coder: NSCoder) {
super.init(coder: coder)
self.layer.addSublayer(underlineLayer)
}
// in `init(frame:)` Add our underlineLayer as a sublayer of the view's main layer
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.addSublayer(underlineLayer)
}
// Any time we are asked to update our subviews,
// adjust the size and placement of the underline layer too
override func layoutSubviews() {
super.layoutSubviews()
setupUnderlineLayer()
}
}
That creates a text field that looks like this:
(And note that if you rotate the simulator to landscape mode, the UnderlineTextField repositions the underline layer for the new text field bounds.)
Note that it might be easier to just add a UIView to your storyboard, pinned to the bottom of your text field and one pixel tall, using your desired underline color. (You'd set up the underline view using AutoLayout constraints, and give it a background color.) If you did that you wouldn't need any code at all.
Edit:
I created a Github project demonstrating both approaches. (link)
I also added a view-based underline to my example app. That looks like this:
I am trying to make my table view cells look "material". Here is something similar to what I want to do (source):
Note that there is a shadow around the whole table view in the above image. What I want is that shadow, but applied to each table view cell, instead of the whole table view.
I first designed my cell in an XIB file. I put a UIView called containerView as a subview of the content view. I added constraints so that the containerView has a top, bottom, left, right margin of 8. This is so that the containerView is a little smaller than the content view, so that the shadow I put on it will be visible.
I also added a UILabel called label as the subview of containerView to show some text.
This is the UITableViewCell subclass:
class QueueItemCell: UITableViewCell {
#IBOutlet var label: UILabel!
#IBOutlet var container: UIView!
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
...
}
override func setSelected(_ selected: Bool, animated: Bool) {
...
}
override func awakeFromNib() {
container.layer.shadowColor = UIColor.black.cgColor
container.layer.shadowOpacity = 0.7
container.layer.shadowOffset = CGSize(width: 3, height: 9)
container.layer.shadowRadius = 4
container.layer.cornerRadius = 4
container.layer.shadowPath = UIBezierPath(roundedRect: container.bounds, cornerRadius: 4).cgPath
selectionStyle = .none
}
}
There is nothing special about the data source and delegate methods except that I set the cells' height to 61 in heightForRowAt.
When I run the app, I got something like this:
The shadow on the bottom and left edges are quite good. But the right edge is a total disaster. The top edge also does not have a shadow, which is undesirable. I tried to do trial and error with shadowPath and shadowOffset but there's always one or two edges that looks bad.
How can I achieve a shadow on all edges of the cell, as shown in the first image?
in awakeFromNib you have wrong view size. You need to move container.layer.shadowPath = UIBezierPath(roundedRect: container.bounds, cornerRadius: 4).cgPath into layoutSubviews
or remove this code
container.layer.shadowPath = UIBezierPath(roundedRect: container.bounds, cornerRadius: 4).cgPath
so shadow will be configured automatically
I am having a problem with one of my table views. I am writing a messaging page for my app that uses a table view to display the messages sent and received. The table cells need to change height based on each cells content. I have the sizing working correctly but I now need to round the cells edges to fit the UI design. The way that I have done this in the past with non-dynamic heights is by calling a function to round each corner in the override function "layoutSubViews()" in the tableViewCell:
func roundAllCorners(radius: CGFloat) {
let allCorners: UIRectCorner = [.topLeft, .bottomLeft, .bottomRight, .topRight]
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: allCorners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
If I try calling this function but the cell is dynamically sized then the left edge cuts off half a centimeter. If you scroll the cell off screen and back again though it fixes it. Hope you can find a solution to my problem, has been a pain in the neck for a while. Thanks.
It might be you also need to override the setter for frame and call it in there. Any any case this is not a good idea for multiple reasons. The thing is that table view cell has many views (including itself being a view) like content view and background view...
I suggest that you add yet another view on the content view which holds all your cell views. Then make this view a subclass and handle all the rounding in there. So from the storyboard perspective you would have something like:
- UITableViewCell
- contentView
- roundedContainer
- imageView
- button
- label
...
The rounded view has (or should have) constraints so layoutSubViews should be enough to override for setting up corner radius.
You can have a neat class you can use to round your view like:
class RoundedView: UIView {
#IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
refresh()
}
}
#IBInspectable var fullyRounded: Bool = false {
didSet {
refresh()
}
}
override func layoutSubviews() {
super.layoutSubviews()
refresh()
}
private func refresh() {
layer.cornerRadius = fullyRounded ? min(bounds.width, bounds.height) : cornerRadius
}
}
As already mentioned by #iDeveloper it might be better to use cornerRadius of a layer. But if you need to use a shape layer you can do that as well in this class.
Make sure to clip bounds on this view.
Make sure you RELOAD THE TABLEVIEW after calling your function
yourTableView.reloadData()
You can use self sizing table view cell according to the content. Now you can follow the previous implementation for rounded corner cell.
Place the below code inside viewDidLoad.
tableView.estimatedRowHeight = YourEstimatedTableViewHeight
tableView.rowHeight = UITableViewAutomaticDimension
Note: You have to give the top and bottom constraints to the content properly.
For detailed implementation you can follow self-sizing-table-view-cells
Here I've got screen designed in Sketch:
There are two buttons. Now I am designing such button in Xcode and I am setting UIButton's corner radius this way:
layer.cornerRadius = 30
clipsToBounds = true
But as the result I am having something strange:
You can see some corner in the center if the left and right sides of button. What can I do?
To generate round corners on such a button, if you set the cornerRadius value to 30, you are assuming that the height of the button is set to 60.
This may not be true on all the devices, depending on how you handle your layout. Seeing your image, it looks like the button is slightly less high than what you designed.
Two options :
Use Auto-Layout and add a constraint of "fixed height" on your button, with a value of 60, so your button always has a height of 60 points.
Implement a UIButton subclass, and in the layoutSubviews method, set the cornerRadius to half the height of the bounds of your button. This way, any time the system re-draws the button, the corner radius will be updated appropriately.
Make a custom UIButton Class and set all of your desired buttons to that class so you don't need to put any more code in every UIViewController class.
The custom UIButton class should look like this:
import UIKit
class RoundCornerButton: UIButton {
override func drawRect(rect: CGRect) {
// Drawing code
self.clipsToBounds = true
self.layer.cornerRadius = self.frame.size.width / 2
}
}
Your button's layer has a different size now, than in Sketch.
After layoutSubviews set the corner radius to be the half of the layers height.
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = layer.bounds.height / 2.0
}
Instead of writing code in every controller if you are going to use multiple times, You can make extension for making circular buttons, views as well using below code.In which you can pass cornerRadius, borderWidth and UIColor.
import UIKit
extension UIView
{
func makeCircular(cornerRadius: CGFloat, borderWidth: CGFloat, borderColor: UIColor)
{
self.layer.cornerRadius = cornerRadius * self.bounds.size.width
self.layer.borderColor = borderColor.CGColor as CGColorRef
self.layer.borderWidth = borderWidth
self.clipsToBounds = true
}
}
you can simply pass the values as per your requirement.
Usage :
snapButton.makeCircular(0.5, borderWidth: 1.0, borderColor: UIColor.clearColor())