2

I was trying to follow this tutorial on building a custom control in iOS: http://www.raywenderlich.com/36288/how-to-make-a-custom-control

I wanted to then try out the @IBDesignable and @IBInspectable properties to see how live rendering worked so I exposed those. I then dropped a UIView on my storyboard and changed the class to the RangeSlider and although it looks ok in the Assistant Editor's preview mode, when I run it in the simulator, it does not actually render the two thumbLayers. When I set a breakpoint in my code, I see that even though setNeedsDisplay is called for the different layers of the custom control, the actual drawInContext methods are never called. To try to reproduce this, I created these two files and the same thing happens, no drawInContext ever gets called.

TestControl.swift
import UIKit

@IBDesignable
class TestControl: UIControl {

    @IBInspectable var cornerRadius: CGFloat = 3.0 {
        didSet {
            updateLayerFrames()
        }
    }

    let testLayer = TestLayer()

    override var frame: CGRect {
        didSet {
            updateLayerFrames()
        }
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

//        testLayer.contentsScale = UIScreen.mainScreen().scale
//        layer.addSublayer(testLayer)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        testLayer.contentsScale = UIScreen.mainScreen().scale
        layer.addSublayer(testLayer)
    }

    func updateLayerFrames() {
        CATransaction.begin()
        CATransaction.setDisableActions(true)

        testLayer.setNeedsDisplay()

        CATransaction.commit()
    }
}


TestLayer.swift
import UIKit
import QuartzCore

class TestLayer: CALayer {

    override func drawInContext(ctx: CGContext!) {
        println("test test")


    }

}


ViewController.swift
    @IBOutlet var testControl: TestControl!

Is there something I'm missing about the process of creating a custom control? Sorry if this is a noob question.

Crystal
  • 28,460
  • 62
  • 219
  • 393
  • It might be checking whether or not the layer has a non-zero frame before calling that. Have you tried explicitly making the frame something? – DanZimm Aug 13 '15 at 00:01
  • One of the inits is called in live preview and the other in the actual app. Since your code for the two is different, I suspect the problem is right there. – MirekE Aug 13 '15 at 00:10
  • @DanZimm well the frame is definitely CGRectZero. The code works if I don't create the view in IB and I just create it with a frame in viewDidLoad. – Crystal Aug 13 '15 at 23:10
  • @Crystal I see. I'm not quite sure what the entire issue is - I'd need like a full project to mess around with, but perhaps checking out [this post](http://stackoverflow.com/questions/26197582/is-there-a-way-for-interface-builder-to-render-ibdesignable-views-which-dont-ov) might help you. – DanZimm Aug 14 '15 at 18:29

0 Answers0