Ios UIButton自定义类

Ios UIButton自定义类,ios,objective-c,uikit,Ios,Objective C,Uikit,您好,我创建了以下代码和一个自定义的ui按钮class myButton.backgroundColor = [UIColor colorWithRed: 0.906 green: 0.298 blue: 0.235 alpha: 1]; myButton.layer.cornerRadius = 5; 如何在自定义的UIButton类中使用此代码,并在所有按钮中使用此代码,而不是为我在项目中创建的每个UIButton复制此代码 您可以创建自定义类继承UIButton类。在这个类上,您可以像以

您好,我创建了以下代码和一个自定义的
ui按钮
class

myButton.backgroundColor = [UIColor colorWithRed: 0.906 green: 0.298 blue: 0.235 alpha: 1];
myButton.layer.cornerRadius = 5;

如何在自定义的
UIButton
类中使用此代码,并在所有按钮中使用此代码,而不是为我在项目中创建的每个
UIButton
复制此代码

您可以创建自定义类继承
UIButton
类。在这个类上,您可以像以前一样自定义属性,并在任何地方使用这个类

@interface YourButton : UIButton

您可以在Objective C中创建UIButton的类别

@interface UIButton ( ExtendButton )

+(UIButton *) myButton;

@end

@implementation UIButton

+(UIButton *) myButton {

UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom];
theButton.backgroundColor = [UIColor colorWithRed: 0.906 green: 0.298 blue: 0.235 alpha: 1];
theButton.layer.cornerRadius = 5;
return theButton;
}

@end

在这里检查这些图片,它可能会帮助你


为名称custombuttonClass创建新的NSObjectClass

custombuttonClass.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface custombuttonClass : NSObject

+(void)custombutton : (UIButton *)btn;

@end
导入CustomButton使用并调用此方法的类 例如:

#import "ViewController.h"
#import "custombuttonClass.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [custombuttonClass custombutton:myButton]; // add your button as a parameter

    // Do any additional setup after loading the view, typically from a nib.
}

使用自定义UIButton子类而不是UIButton。您可以继承UIButton的一个类,这样您可以将这些行添加到该类中,而不是mybutton,您可以使用self.backgroundcolor并将该类添加到故事板中的button只需将此代码粘贴到自定义UIButton类中,并为所有UIButton继承自定义类即可真的明白我对目标c是新手
#import "ViewController.h"
#import "custombuttonClass.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [custombuttonClass custombutton:myButton]; // add your button as a parameter

    // Do any additional setup after loading the view, typically from a nib.
}