[英]How to reuse properties
我的應用程序中有許多不同的按鈕,但是大多數按鈕具有分配給它們的相同屬性:
login = [[UIButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)];
[login setTitle:@"Login" forState:UIControlStateNormal];
[login.titleLabel setFont:[UIFont fontWithName:@"Avenir Next" size:18]];
[login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[login setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateHighlighted];
[login setTitleColor:[UIColor colorWithWhite:0.5 alpha:1] forState:UIControlStateDisabled];
有什么方法可以創建一個已經分配了這些默認屬性的類或某個按鈕? 所以我可以簡單地執行以下操作:
CustomButtom *btn = [CustomButton alloc]init];
那么btn
將分配所有上述屬性嗎?
謝謝。
解決此問題的另一種方法是,您可以創建一個私有方法,該方法將返回具有相同屬性的UIButton。 我認為創建UIButton的子類是不必要的。
您可以通過創建CustomButton類來做到這一點
Xcode-> 新文件 -> 可可觸摸類 -> 下一步 ->命名您的按鈕->選擇UIButton的 子類
CustomButton.h文件
#import <UIKit/UIKit.h>
@interface CustomButton : UIButton
@end
CustomButton.m文件
#import "CustomButton.h"
@implementation CustomButton
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
//login = [[UIButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)];
[self setTitle:@"Login" forState:UIControlStateNormal];
[self.titleLabel setFont:[UIFont fontWithName:@"Avenir Next" size:18]];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateHighlighted];
[self setTitleColor:[UIColor colorWithWhite:0.5 alpha:1] forState:UIControlStateDisabled];
}
@end
現在,給您打電話
CustomButton *customButton = [[CustomButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)];
[customButton addTarget:self action:@selector(loginButtonPressed:) forControlEvents:UIControlEventTouchDown];
[YourView addSubview:customButton];
您有兩種選擇:
UIButton
的函數,以為您設置屬性 是。 您可以將UIButton子類化。 當您覆蓋init方法設置屬性時,可以獲得具有相同屬性的按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.