自定义多个标签或按钮

Customize multiple labels or buttons

在我的 objective-c 代码中,我自定义了不同的标签和 UIButton,但我不知道如何将它们一起编辑,例如:

[[CincKmButton layer] setCornerRadius:10];
[CincKmButton setClipsToBounds:YES];
[[CincKmButton layer] setBorderColor:
 [[UIColor colorWithRed:0 green:0 blue:0 alpha:1] CGColor]];
[CincKmButton setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"pickerBackground.jpg"]]];
[[CincKmButton layer] setBorderWidth:2.75];

[[DeuKmButton layer] setCornerRadius:10];
[DeuKmButton setClipsToBounds:YES];
[[DeuKmButton layer] setBorderColor:
 [[UIColor colorWithRed:0 green:0 blue:0 alpha:1] CGColor]];
[DeuKmButton setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"pickerBackground.jpg"]]];
[[DeuKmButton layer] setBorderWidth:2.75];

[[HalfButton layer] setCornerRadius:10];
[HalfButton setClipsToBounds:YES];
[[HalfButton layer] setBorderColor:
 [[UIColor colorWithRed:0 green:0 blue:0 alpha:1] CGColor]];
[HalfButton setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"pickerBackground.jpg"]]];
[[HalfButton layer] setBorderWidth:2.75];

怎么才能不每次都重复呢?谢谢!

创建 UIButton 的子 class 并将这些属性写入 class。

并使用创建的 Class 而不是 UIButton

否则

[[UIButton appearance] setClipsToBounds:YES];
[[UIButton appearance].layer setCornerRadius:10.0];
//similarly apply all properties to appearance class, this will automatically get applied to all UIButtons 

你可以做到:

CincKmButton.layer.cornerRadius = DeuKmButton.layer.cornerRadius  = 10;
CincKmButton.backgroundColor = DeuKmButton.backgroundColor  = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pickerBackground.jpg"]];

或者创建一个 UIButton 的 NSMutableArray 并使用 "for"

同时编辑所有内容

或者您可以创建一个 UIButton 子类来使用方法设置所有这些属性。

您可以创建一个方法并将按钮发送给它。

-(void) assignButtonProperties :(UIButton *)sampleButton
{
   [[sampleButton layer] setCornerRadius:10];
   [sampleButton setClipsToBounds:YES];
   [[sampleButton layer] setBorderColor: [[UIColor colorWithRed:0 green:0 blue:0 alpha:1] CGColor]];
   [sampleButton setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"pickerBackground.jpg"]]];
   [[sampleButton layer] setBorderWidth:2.75];
}

例如:

[self assignButtonProperties : CincKmButton];
[self assignButtonProperties : DeuKmButton];

最简单的方法可能是创建一个 NSArray 按钮和一个进行自定义的方法。它最终看起来像

...
for (UIButton *button in @[CincKmButton,DeuKmButton,HalfButton]) {
    [self configureButton:button]
}
...

- (void) configureButton:(UIButton *)button {
    [button setClipsToBounds:YES];
    button.layer.cornerRadius = 10;
    button.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1].CGColor;
    button.layer.borderWidth = 2.75;
    [button setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"pickerBackground.jpg"]]];
}