在Objective C中自定义现有按钮

时间:2017-02-14 16:58:38

标签: ios objective-c uibutton

我希望能够自定义我在应用程序的特定样式中创建的任何按钮。我正在尝试创建一个包含所有设置的新类,因此每次添加新按钮时,我都可以使用该类的方法来自定义新按钮。

我是iOS编程的新手,所以我觉得我可能做错了什么,但这就是我到目前为止所做的:

我用设置

创建了这个类
#import "CustomButton.h"

@implementation CustomButton

-(UIButton *) setButtonWithType{

    self.layer.cornerRadius = 25;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(1.5f, 1.5f);
    self.layer.shadowOpacity = 1.0f;
    self.layer.shadowRadius = 0.0f;
    self.layer.masksToBounds = NO;

    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.bounds;
    gradient.startPoint = CGPointMake(0.5, 0.5);
    gradient.endPoint = CGPointMake(0.0, 0.5);
    gradient.colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor,(id)[UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0].CGColor, nil];
    gradient.cornerRadius = self.layer.cornerRadius;
    [self.layer insertSublayer:gradient atIndex:0];

    return self;
}

@end

ViewController.h

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIButton *button;

@end

ViewController.m

#import "ViewController.h"
#import "CustomButton.h"

@interface ViewController ()


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    CustomButton *btn = [[CustomButton alloc] init];


    self.button = [btn setButtonWithType]; 

//rest of the code

任何想法如何使其有效? 或者我需要使用一种非常不同的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

你可能会发现成功做这个类别(很多例子)......

的UIButton + ShadowRoundedGradient.h

#import <UIKit/UIKit.h>

@interface UIButton (ShadowRoundedGradient)

- (void) makeMe;

@end

的UIButton + ShadowRoundedGradient.m

#import "UIButton+ShadowRoundedGradient.h"

@implementation UIButton (ShadowRoundedGradient)

- (void) makeMe {

    self.layer.cornerRadius = 25;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(1.5f, 1.5f);
    self.layer.shadowOpacity = 1.0f;
    self.layer.shadowRadius = 0.0f;
    self.layer.masksToBounds = NO;

    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.bounds;
    gradient.startPoint = CGPointMake(0.5, 0.5);
    gradient.endPoint = CGPointMake(0.0, 0.5);
    gradient.colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor,(id)[UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0].CGColor, nil];
    gradient.cornerRadius = self.layer.cornerRadius;
    [self.layer insertSublayer:gradient atIndex:0];

}

@end

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {

@property (weak, nonatomic) IBOutlet UIButton *button;

}

@end

ViewController.m

#import "ViewController.h"
#import "UIButton+ShadowRoundedGradient"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.button makeMe];

    //rest of the code
}