开发者

iPhone/iPad stretchy, resizable buttons - subclassing UIButton

开发者 https://www.devze.com 2023-01-20 19:13 出处:网络
I want to be able to make custom buttons which have an image background using a scale9 type background image meaning the width of the button can be dynamic. I have seen example on the web of people do

I want to be able to make custom buttons which have an image background using a scale9 type background image meaning the width of the button can be dynamic. I have seen example on the web of people doing this on a per button basis but it seems to me that wouldn't it be better to create a new object which subclasses UIButton which you can then use in Interface Designer as the class for any custom button (round rect butto开发者_如何转开发n set to custom).

Here is what I have so far.

#import <Foundation/Foundation.h>

@interface LargeButton : UIButton {
}

@end

#import "LargeButton.h"


@implementation LargeButton

- (id)initWithFrame:(CGRect)frame {
 if (self = [super initWithFrame:frame]) {

  self.frame = CGRectMake(0, 0, 170.0, 48.0);

  // Center the text vertically and horizontally
  self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
  self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

  UIImage *image = [UIImage imageNamed:@"btnBigPurple.png"];

  // Make a stretchable image from the original image
  UIImage *stretchImage = 
  [image stretchableImageWithLeftCapWidth:15.0 topCapHeight:0.0];

  // Set the background to the stretchable image
  [self setBackgroundImage:image forState:UIControlStateNormal];

  // Make the background color clear
  //self.backgroundColor = [UIColor clearColor];
 }
 return self;
}

@end

This doesn't however seems to work. When I run this im simulator I see the button text but the button has no background. I have placed a breakpoint and I know its running and check the console and have no errors.

Can someone help? fix this or is my way of thinking wrong?

Thanks


I fixed it myself. For those who are interested.

#import <Foundation/Foundation.h>


@interface LargeButton : UIButton {
}

@end

#import "LargeButton.h"


    @implementation LargeButton

    - (void)drawRect:(CGRect)rect{
        UIImage *greenBalloon = [[UIImage imageNamed:@"btnBigPurple.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
        [self setBackgroundImage:greenBalloon forState:UIControlStateNormal];
    }

    @end

Simple but effective.

0

精彩评论

暂无评论...
验证码 换一张
取 消