Why does CGContext not work in UITableViewCell on iOS 14? - ios

Drawing lines doesn't work on iOS 14.
I create a subclass of UITableViewCell.
I want to draw two lines in the custom cell.
The code is below.
override func draw(_ rect: CGRect) {
super.draw(rect);
guard let context = UIGraphicsGetCurrentContext() else { return }
context.saveGState() // Save state. This includes transformations and clips
context.setLineWidth(8.0)
let lineColor = UIColor.red
let bgColor = UIColor.lightGray
context.setStrokeColor(bgColor.cgColor)
context.move(to: CGPoint(x: 86.0, y: 42))
context.addLine(to: CGPoint(x: (86.0 + 120.0), y: 42))
context.setLineCap(.round)
context.strokePath()
context.setLineWidth(8.0)
context.setStrokeColor(lineColor.cgColor)
context.move(to: CGPoint(x: 86.0, y: 42))
context.addLine(to: CGPoint(x: (86.0 + 120.0 * self.lineScale ), y: 42))
context.setLineCap(.round)
context.strokePath()
context.restoreGState() // Put back state. This includes transformations and clips
}
It works well on iOS 12. It doesn't work on iOS 14. (I don't know whether it works on iOS 13).
I don't know what I can do to solve this issue.
Do you know the reason? Can you fix it?

You should not be trying to override draw(_ rect: CGRect) for a table view cell to begin with. Cells have subviews, which have subviews, and the cell itself does a lot more than just "be there."
If you use Debug View Hierarchy you will see what's going wrong, and it will reinforce why that's a bad idea.
With iOS 14 the cell structure changed and you should only be manipulating the cell's .contentView -- not the cell itself.
Much better to make that a custom view which is added to the content view.

You shouldn't override the draw(_ rect: CGRect) of a table cell. Instead, create a new custom view and add it to the cell's contentView, and draw in there.
You should instead create your UIView and add it as a subview of the contentView property. There are many questions/answers on here and across the web about drawRect: and UITableViewCell, most of them suggest that you do not do it.

Related

iOS Swift draw to screen

I am new to iOS development and need help from someone a bit more experienced than me. I searched the internet and couldn't find any working solution.
I need to draw to the screen like canvas in Android. Currently I have a CADisplayLink to call a function every frame. And that's working well. The problem is: How do I actually draw anything, like a rectangle, a circle or a line to the screen every frame?
This is what I have (I linked this class to the view in the storyboard):
class Canvas: UIView {
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(2.0)
context?.setStrokeColor(UIColor.green.cgColor)
context?.move(to: CGPoint(x: 30, y: 30))
context?.addLine(to: CGPoint(x: Double(xBall), y: Double(yBall)))
context?.strokePath()
}
}
With the following code I can actually draw a line to the screen:
let canvas = Canvas()
canvas.draw(CGRect())
The problem is, that this works exactly ONE time. When I have canvas.draw(CGRect()) in my loop which repeats every frame, it works for the first frame (the initial values of xBall and yBall) and never again. When I print the values in the draw method, it gets called every frame and the variables have the correct values. But it does not draw it to the screen. I tried adding the line setNeedsDisplay() in the draw method, with similar results.
Any help will be appreciated! Thanks!
If you refer to the draw(_:) documentation, it says:
This method is called when a view is first displayed or when an event occurs that invalidates a visible part of the view. You should never call this method directly yourself. To invalidate part of your view, and thus cause that portion to be redrawn, call the setNeedsDisplay() or setNeedsDisplay(_:) method instead.
The common approach would be to have your view controller viewDidLoad method add Canvas view:
override func viewDidLoad() {
super.viewDidLoad()
let canvas = Canvas()
canvas.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(canvas)
NSLayoutConstraint.activate([
canvas.leadingAnchor.constraint(equalTo: view.leadingAnchor),
canvas.trailingAnchor.constraint(equalTo: view.trailingAnchor),
canvas.topAnchor.constraint(equalTo: view.topAnchor),
canvas.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
You don’t call draw(_:) yourself, but rather the OS will do so automatically. All you need to do is add it to your view hierarchy with addSubview(_:). And you can then just have your CADisplayLink update the properties and call setNeedsDisplay (or, better, add didSet observers to those properties that calls setNeedsDisplay for you).
By the way, if you don’t want to add this programmatically, like shown above, you can add Canvas right in Interface Builder. Just drag a UIView onto your storyboard scene, add all of the appropriate constraints, go to the “identity” inspector, and set the base class name to be Canvas:
And if you mark your class as #IBDesignable, you can actually see your path rendered right in Interface Builder, like shown above.
A number of refinements:
If you are going to implement draw(_:) yourself, instead of getting a graphics context with UIGraphicsGetCurrentContext, you might just stroke a UIBezierPath:
override func draw(_ rect: CGRect) {
let path = UIBezierPath()
path.move(to: CGPoint(x: 30, y: 30))
path.addLine(to: CGPoint(x: xBall, y: yBall))
path.lineWidth = 2
UIColor.green.setStroke()
path.stroke()
}
Like your solution, this requires that after you update xBall and yBall, if you call setNeedsDisplay to have the view re-rendered with the updated path.
Sometimes we wouldn’t even implement draw(_:). We would just add a CAShapeLayer as a sublayer:
#IBDesignable
class Canvas: UIView {
var xBall = ...
var yBall = ...
let shapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.green.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 2
return shapeLayer
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
func configure() {
layer.addSublayer(shapeLayer)
updatePath()
}
func updatePath() {
let path = UIBezierPath()
path.move(to: CGPoint(x: 30, y: 30))
path.addLine(to: CGPoint(x: xBall, y: yBall))
shapeLayer.path = path.cgPath
}
}
In this sort of approach, you just update the path of the shapeLayer and the OS will render your shape layer (and its path) for you.

Changing colour of path drawn in UIView draw(_rect)

I have drawn a circle using addArc in my UIView subclass' draw(_ rect: CGrect) function. It draws fine initially, but when some UI trigger occurs, I wanted to change the fill colour of the circle by changing the value of a isFilledIn property.
However, my circles do not change when the isFilledIn property is modified. The isFilledIn property and the draw method are both being called as expected, but the appearance of the circle does not change. It seems once the circles are drawn, their appearance is stuck.
var isFilledIn = false {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
context.setLineWidth(outlineWidth)
myOutlineColor.setStroke()
if isFilledIn {
myFilledColor.setFill()
} else {
myEmptyColor.setFill()
}
let center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
let radius = (frame.size.width - 10) / 2
context.addArc(center: center, radius: radius, startAngle: 0.0, endAngle: .pi * 2.0, clockwise: true)
context.drawPath(using: .fillStroke)
}
}
I tried adding a context.clear(rect) but that had no effect. I also considered saving the CGPath to a property and just trying to modify that instead of calling setNeedsDisplay but I wasn't sure how to apply the fill colour changes if all I have is a CGPath.
I realize there are other, potentially easier / more efficient ways to create circles (e.g. UIBezierPath, or a UIView with a corner radius), but I'm specifically trying to understand Core Graphics better and I want to understand why this doesn't work.
Was calling my view setup code in layoutSubviews, forgetting that that method may be called multiple times (and it was). So as Sulthan pointed out in the comments above, I did have overlapping views. There was a second circle on top of the one I was trying to redraw.
Adding an if statement inside layoutSubviews to prevent it from setting up the circle multiple times fixed it for me.
Thank you Sulthan.

How to get UIImageView's subview (a UIView) to cover it entirely?

I have a UIImageView placed on the storyboard, and am trying to programmatically add a UIView as a subview to it, and have that UIView match the parent UIImageView's size and position exactly so that it covers it.
The UIView is a custom class of UIView thats drawing a CAShapeLayer that fills its frame, if that matters at all.
In addition to the following code, I've also tried "redOverlay.center = parentImage.center" without success.
In my viewdidload() i have:
let redOverlay = RedOverlay(frame: CGRect(x: 0.0, y: 0.0, width: parentImage.bounds.width, height: parentImage.bounds.height))
parentImage.addSubview(redOverlay)
And here is my RedOverlay subclass of UIView if that makes a difference:
import UIKit
extension CGFloat {
func toRadians() -> CGFloat {
return self * CGFloat.pi / 180.0
}
}
class RedOverlay: UIView {
var path: UIBezierPath!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.darkGray.withAlphaComponent(0.5)
pie()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func pie() {
path = UIBezierPath()
path.move(to: CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2))
path.addArc(withCenter: CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2),
radius: self.bounds.size.width/2,
startAngle: CGFloat(215).toRadians(),
endAngle: CGFloat(90).toRadians(),
clockwise: true)
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.opacity = 0.5
self.layer.addSublayer(shapeLayer)
}
}
The result I get actually works perfectly on iPhone 6, but anything larger like 6s or ipads, and the child UIView is actually noticeably smaller than the UIImageView. In the iPad, the UIView sits well to the left, while in the 6s it is only a bit left.
Basically, it seems like the UIView being generated isnt as wide as the image, even though parentImage.bounds.width was used to determine the UIView's width. I do have "Clip to Bounds" and Aspect Fit set in IB so I don't know why the image would be bigger than it's bounds if thats possible at all.
Whats the cleanest way to get this subview to match the parent view in all device sizes?
EDIT: The solution I found was to call my function pie() (that draws the CAShapeLayer), by overriding layoutSubviews and calling pie() there so that my shapeLayer is updated whenever the view changes. I removed .addSublayer(shapeLayer) from pie() and now I call it in viewdidload in case layoutsubviews being called repeatedly might cause many layers to be created.
override func layoutSubviews() {
super.layoutSubviews()
pie()
}

Ios - Is there a way to draw a line in UIViewController without using code

I want to draw a line in UIViewController without using code, so like the constraints for the lines can be given in storyboard itself. if there is a way to do it, please tell me. Now i have drawn a line by placing an UIView in storyboard and used the following code to draw line on it. Is this the best way ?. Or do i have any better way ?. Thanks in advance.
class line: UIView {
override func draw(_ rect: CGRect) {
let aPath = UIBezierPath()
aPath.move(to: CGPoint(x:0, y:1))
aPath.addLine(to: CGPoint(x:500, y:1))
//Keep using the method addLineToPoint until you get to the one where about to close the path
aPath.close()
//If you want to stroke it with a red color
UIColor.blue.set()
aPath.stroke()
//If you want to fill it as well
aPath.fill()
}
}
Using Swift 3.0 and Xcode 8.2
Use #IBDesignable as follows. Make your view with height of one as suggested and the #IBDesignable will show your line in your storyboard.:
import UIKit
#IBDesignable class line: UIView {
override func draw(_ rect: CGRect) {
let aPath = UIBezierPath()
aPath.move(to: CGPoint(x: 0, y: 1))
aPath.addLine(to: CGPoint(x: 250, y: 1))
aPath.close()
UIColor.blue.set()
aPath.stroke()
}
}
Add a UIView with a height of 1 point.
Add constraints for it.

How to create unique shapes or UIViews in Swift

I don't really have any knowledge of drawing in Swift, but I'm looking to create part of my app background that's slightly different to a square. See the image below for what I'm trying to make:
The idea is that this will sit at the top of the screen, and be nothing more than a background. It'll stretch half way down the screen. I'll then add an image over the top etc. I would need the point at the bottom of the square to always sit in the middle of the screen.
Can I make this shape/UIView in Swift by code? And if so, how?
Or, is it better to just create this as an image and do it that way?
Can I make this shape/UIView in Swift by code? And if so, how?
Views are always rectangular, but a view's content can be any shape at all and it's background can be transparent, so the visible part of a view can be anything you can draw.
There are a lot of ways to draw something in iOS. It's usually best to start with the highest level tool that'll work for you and move down to a lower level when you need more control. With that in mind, I'd suggest starting by creating a view that draws your pentagon using a UIBezierPath. The (Swift 5) code for this is very simple:
class PentagonView : UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.clear
}
override func draw(_ rect: CGRect) {
let size = self.bounds.size
let h = size.height * 0.85 // adjust the multiplier to taste
// calculate the 5 points of the pentagon
let p1 = self.bounds.origin
let p2 = CGPoint(x:p1.x + size.width, y:p1.y)
let p3 = CGPoint(x:p2.x, y:p2.y + h)
let p4 = CGPoint(x:size.width/2, y:size.height)
let p5 = CGPoint(x:p1.x, y:h)
// create the path
let path = UIBezierPath()
path.move(to: p1)
path.addLine(to: p2)
path.addLine(to: p3)
path.addLine(to: p4)
path.addLine(to: p5)
path.close()
// fill the path
UIColor.red.set()
path.fill()
}
}
And now you can use that view anywhere in your UI:
If you want to add a 150x150px PentagonView to your view controller's main view at coordinates (100, 200), you could put the following in viewDidLoad():
let pg = PentagonView(frame:CGRect(x:100, y:200, width:150, height:150))
self.view.addSubview(pg)
Or, you could also add a PentagonView to some view in your storyboard by dropping in a UIView of the right size and then changing it's class to PentagonView.
Or, is it better to just create this as an image and do it that way?
If you've fully described your requirement, then no, I don't think so: the image itself will probably be a lot larger than the code that draws it, and the code that I've given above will work at any size you choose. On the other hand, if you're going to add a lot of complex detail, and if the image only needs to appear at one size, then it might be easier to create it once in a drawing program and store that work as an image. Like I said above, there are a lot of options for drawing in iOS; which you choose should be determined by your needs.
Caleb's answer updated to Swift 5:
class PentagonView : UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = .clear
}
override func draw(_ rect: CGRect) {
let size = self.bounds.size
let h = size.height * 0.85 // adjust the multiplier to taste
// calculate the 5 points of the pentagon
let p1 = self.bounds.origin
let p2 = CGPoint(x:p1.x + size.width, y:p1.y)
let p3 = CGPoint(x:p2.x, y:p2.y + h)
let p4 = CGPoint(x:size.width/2, y:size.height)
let p5 = CGPoint(x:p1.x, y:h)
// create the path
let path = UIBezierPath()
path.move(to: p1)
path.addLine(to: p2)
path.addLine(to: p3)
path.addLine(to: p4)
path.addLine(to: p5)
path.close()
// fill the path
UIColor.red.set()
path.fill()
}
}
The best way to tackle this is not by creating a view (UIView) but a layer (CAShapeLayer). You can create a CAShapeLayer from a path, thus describing your shape with vectors (as opposed to a bitmap).
There are many tutorials about CAShapeLayer that will show you code for achieving this.
It would probably be best if you loaded an image from file of the shape onto a UIImageView, especially if its just a background. You can then constraint the bottom of the view to the middle of your app. You might also be able to do some tweaking of the view's CALayer property to achieve your effect however.

Resources