Jeef
Jeef

Reputation: 27285

From SWIFT Playground to custom View (IBDesignable?)

Question:

I've written a custom View Component in a playground but I can't figure out how to turn it into a custom class that I can use in the Interface Builder. Specifically, I'm confused as to how to make sure my custom view will resize correctly as the IB view is changed

Sub Question

Playground Code

import UIKit
let labelWidth : CGFloat = 200.0
var viewWidth  : CGFloat = 200.0
let labelHeight: CGFloat = 60.0
var viewHeight : CGFloat = 60.0

let xOffset : CGFloat = 20
let yOffset : CGFloat = 20


let label = UILabel(frame: CGRectMake(0, 0 + 10, labelWidth, 50))

label.text = "Custom Text"


label.backgroundColor = UIColor.greenColor()
label.layer.masksToBounds = true
//label.layer.cornerRadius = 10.0
label.textAlignment = NSTextAlignment.Center

label

let titleLabel = UILabel(frame: CGRectMake(0,0,labelWidth,20))
titleLabel.font = UIFont(name: label.font.fontName, size: 10)
titleLabel.text = "  TITLE"
titleLabel.layer.masksToBounds = true
titleLabel.backgroundColor = UIColor.whiteColor()
titleLabel

let v = UIView(frame: CGRectMake(0, 0, viewWidth, viewHeight))

v.backgroundColor = UIColor.grayColor()
v.addSubview(label)
v.addSubview(titleLabel)

v.layer.borderWidth = 1
v.layer.borderColor = UIColor.redColor().CGColor

v

Playground Visual Output

enter image description here

Note: Obviously these are not the final colors i want to use but they help differentiate the components

Upvotes: 1

Views: 784

Answers (1)

zisoft
zisoft

Reputation: 23078

I just posted this answer for a similar question.

Here is a sample class to get you started.

import UIKit

@IBDesignable
class MyTabView: UIView {
    @IBInspectable tabTitle: String = ""
    @IBInspectable tabColor: UIColor = UIColor.clearColor()

    override init(frame: CGRect) {
        super.init(frame: frame)
        // Initialization code
    }

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

    override func prepareForInterfaceBuilder() {
        // stuff for interface builder only
    }

    override func drawRect(rect: CGRect)
    {
        // this is where your view gets drawed
        self.layer.cornerRadius = 10
        self.layer.masksToBounds = true
    }
}

Note: you only need to override drawRect if you need custom drawing.

Upvotes: 1

Related Questions