I am trying to use a Swift function to place a circle in the centre of a view so it is always on centre regardless of screen size. I can draw the circle at a point defined by a set of arbitrary x and y values but I need the function to supply these values instead.
I have created a function called screenCentre()
to read and return two parameters that are the centre coordinates. However Xcode warns that the
“Result of call to screenCentre() is unused”
I’ve worked through Swift tutorials on functions and closures and understand how to pass arguments to a function but I am still not clear how to use values returned by this function.
Here is my code:
import UIKit
class ViewController: UIViewController {
let radius = CGFloat(20)
let fillColour = UIColor.clear.cgColor
let lineColour = UIColor.red.cgColor
let lineWidth = 1.0
var x: CGFloat?
var y: CGFloat?
override func viewDidLoad() {
super.viewDidLoad()
screenCentre()
print(screenCentre())
// arbitrary set of coordinates used to draw circle
circle(x: 150, y: 170)
}
func screenCentre() -> (x: CGFloat, y: CGFloat)
{
return (self.view.bounds.size.width / 2, self.view.bounds.size.height / 2)
}
func circle(x: CGFloat, y: CGFloat) {
let circlePath = UIBezierPath(arcCenter: CGPoint(x: x,y: y), radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = fillColour
shapeLayer.strokeColor = lineColour
shapeLayer.lineWidth = CGFloat(lineWidth)
view.layer.addSublayer(shapeLayer)
}
}
UPDATE
By declaring a constant I am able to use values returned by this function. Sam_M and Kevin Bunarjo answered the question as asked.
However Daniel T and PEEJWEEJ both identified a related problem I hadn’t recognised. Once I applied fixits the extension solution offered by Daniel T now gives me a way to rotate the screen around the centre. So I marked it as the best answer. Thanks to everyone who contributed.
Here is the updated code.
let centre = UIScreen.main.centre
circle(x: centre.x, y: centre.y)
}
func screenCentre() -> CGPoint {
return CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)
}