有没有办法实现这个功能?我想让我下载的自定义字体在每个UIButton上显示。
IBOutletCollection
,那么这应该是直接的。@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *buttons;
将按钮连接到此出口集合,然后使用以下方法一次性更改字体:
[self setValue:[UIFont fontWithName:@"Helvetica" size:30] forKeyPath:@"buttons.font"];
Helvetica
的情况下,它将是 Helvetica-Bold
。它大多是可预测的,但不能保证。请查看字体名称这里
。 - Deepak Danduprolu编辑
//
// MyUIButton.h
//
@interface MyUIButton : UIButton {
}
+ (id)buttonWithType:(UIButtonType)buttonType;
@end
//
// MyUIButton.m
//
#import "MyUIButton.h"
@implementation MyUIButton
+ (id)buttonWithType:(UIButtonType)buttonType{
UIButton *button = [UIButton buttonWithType:buttonType];
[[button titleLabel] setFont:[UIFont fontWithName:@"Helvetica-Bold" size:12]];
return button;
}
@end
Then just use it like this:
[MyUIButton buttonWithType:UIButtonTypeCustom]
//
// UIButton+Font.h
//
#import <Foundation/Foundation.h>
@interface UIButton (DefaultFontExtension)
+ (id)buttonWithType:(UIButtonType)buttonType;
@end
//
// UIButton+Font.m
//
#import "UIButton+Font.h"
@implementation UIButton (DefaultFontExtension)
+ (id)buttonWithType:(UIButtonType)buttonType{
UIButton *button = [UIButton buttonWithType:buttonType];
[[button titleLabel] setFont:[UIFont fontWithName:@"Helvetica-Bold" size:12]];
return button;
}
@end
button.titleLabel.font = [UIFont fontWithName:FONT_NAME size:FONT_SIZE];
苹果的文档非常好。首先尝试在那里查找,然后搜索SO(Stack Overflow),再搜索Google,最后再写一个问题。 :)
编辑:
最简单的方法是将任何fontWithName
参数替换为常量,例如宏。
#define BUTTON_FONT_NAME @"Helevetica"
//MYButton.m
-(id) initWithTitle: (NSString *)title {
self.titleLabel = title;
self.titleLabel.font = [UIFont fontWithName: FONT_NAME size FONT_SIZE];
}
然后只需将所有的UIButtons更改为MYButtons即可。
UIButton *NameBtn=[UIButton buttonWithType:UIButtonTypeCustom];
NameBtn=[[UIButton alloc]init];
[NameBtn setBackgroundColor:[UIColor clearColor]];
[NameBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
NSString *textb=[[self.searchList objectAtIndex:indexPath.row] objectForKey:@"name"];
CGSize constraintb = CGSizeMake(310 ,10);
CGSize sizeb = [textb sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraintb lineBreakMode:UILineBreakModeWordWrap];
[NameBtn setTitle:textb forState:UIControlStateNormal];
NameBtn.font = [UIFont fontWithName:@"Helvetica-Bold" size: 12.0];
NameBtn.frame = CGRectMake(85, 12, MAX(sizeb.width ,3.0f),12);
[NameBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
NameBtn.tag=indexPath.row;
[cell addSubview:NameBtn];