1

So i've been playing around with PaintCode and StyleKits in Xcode. I made a button, created a UIView with it's own subclass, and it shows up fine in my ViewController and on my device. However, I want to transform this UIView into a UIButton, as I want code to execute when it's tapped. How would i go about doing this?

thanks guys and have a good one :)

2 Answers2

2

I use PaintCode's UIImage method, and use that UIImage as the UIButton's image. Here's code I use, which is in ObjC, but should be easily converted to Swift.

PaintCode's generated code - the stuff you don't need to write (pretend this class is called PaintCodeClass):

+ (UIImage*)imageOfIcon
{
   if (_imageOfIcon)
        return _imageOfIcon;

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(30, 30), NO, 0.0f);
    [PaintCodeClass drawIcon];

    _imageOfIcon = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return _imageOfIcon;
}

and my code:

UIImage *image = [PaintCodeClass imageOfIcon];
UIButton *button = (initialize, set frame, etc)
[button setImage:image forState:UIControlStateNormal];

Some people like this better:

[button setBackgroundImage:image forState:UIControlStateNormal];

Instead of all that, if you really wanted to, you could do:

[button addSubview:whateverThePaintCodeViewIsCalled];

but that wouldn't behave like a button - so you probably don't want to do that.

Mitch Cohen
  • 1,551
  • 3
  • 15
  • 29
  • Thank you so much for your response. I originally used a TapGestureRecognizer on the UIView and then created a segue to another VC, but then I found a more elegant solution. I created a new subclass for UIButton and used the same StyleKit drawing method. Then, I dragged a button in interface builder and changed the class to the subclass that I defined. Worked like magic. – Aditya Rudrapatna Jul 23 '16 at 08:12
0

@Mitch Cohens answers in Swift 4.1:

static var icon: UIImage {
    UIGraphicsBeginImageContextWithOptions(CGSize.init(width: 50, height: 50), false, 0.0)
    PaintCodeClass.drawIcon()
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

Usage:

button.setImage(PaintCodeClass.icon, for: .normal)

Baran
  • 2,710
  • 1
  • 23
  • 23