I've been stumbling along with Swift lately, and have come across a concept that I think I understood, but can't seem to get it working properly.
In my app, I have a ViewController with a View that I've added in IB. I've set the Custom Class of my View to be "RingView", which lives in my RingView.swift file (for context, RingView draws a ring).
This is technically working fine, as my ring is rendered appropriately when I run the app. What I'm trying to do is to set the width of the ring's line and the stroke color programmatically from my ViewController.swift file. While I'm not getting any errors when I build, despite me setting the lineWidth to 10, for example, the width of the line is always 1 when I build.
RingView.swift
class RingView: UIView {
var lineWidth: CGFloat = 1
var strokeColor = UIColor(red: 147.0/255.0, green: 184.0/255.0, blue: 255.0/255.0, alpha: 1.0).CGColor
let circlePathLayer = CAShapeLayer()
let circleRadius: CGFloat = 105.0
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
func configure() {
circlePathLayer.frame = bounds
circlePathLayer.lineWidth = lineWidth
circlePathLayer.fillColor = UIColor.clearColor().CGColor
circlePathLayer.strokeColor = strokeColor
layer.addSublayer(circlePathLayer)
backgroundColor = UIColor.clearColor()
}
func circleFrame() -> CGRect {
var circleFrame = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius)
circleFrame.origin.x = CGRectGetMidX(circlePathLayer.bounds) - CGRectGetMidX(circleFrame)
circleFrame.origin.y = CGRectGetMidY(circlePathLayer.bounds) - CGRectGetMidY(circleFrame)
return circleFrame
}
func circlePath() -> UIBezierPath {
return UIBezierPath(ovalInRect: circleFrame())
}
override func layoutSubviews() {
super.layoutSubviews()
circlePathLayer.frame = bounds
circlePathLayer.path = circlePath().CGPath
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet var titleLabel: UILabel!
@IBOutlet weak var RingViewInner: RingView!
var detailItem: Minion? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
//Set the label for the title name
if let label = titleLabel {
label.text = detail.title!
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
RingViewInner?.strokeColor = UIColor(red: 255.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 0.0).CGColor
RingViewInner?.lineWidth = 10
RingViewInner.setNeedsDisplay()
//Show the configured context of data
self.configureView()
}
}
Any thoughts would be immensely appreciated. Thank you!
drawRect()in your custom view class to do the drawing of your view. Don't know if that'll solve you issue or not, but it may help.