一.Objective-C版
.h文件
#import <Foundation/Foundation.h>
/**
* 这个分类为UILabel添加一些有用的方法
*/
@interface UILabel (WLKit)
/**
* 创建一个UILabel
*
* @param frame 文字的坐标
* @param text 文字的内容
* @param font 文字的字体
* @param textColor 文字的字体颜色
* @param alignment 文字的对齐方式
*
* @return 返回一个创建好的UILabel
*/
+ (UILabel *_Nonnull)labelWithFrame:(CGRect)frame
text:(NSString *_Nonnull)text
font:(UIFont *_Nullable)font
textColor:(UIColor *_Nullable)textColor
alignment:(NSTextAlignment)alignment;
@end
.m文件
#import "UILabel+WLKit.h"
@implementation UILabel (WLKit)
+ (UILabel * _Nonnull)labelWithFrame:(CGRect)frame
text:(NSString * _Nonnull)text
font:(UIFont * _Nullable)font
textColor:(UIColor * _Nullable)textColor
alignment:(NSTextAlignment)alignment
{
UILabel *label = [[UILabel alloc] initWithFrame:frame];
if (font) {
[label setFont:font];
}
if (text && text.length) {
[label setText:text];
}
[label setBackgroundColor:[UIColor clearColor]];
if (textColor) {
[label setTextColor:textColor];
}
if (alignment) {
[label setTextAlignment:alignment];
}
return label;
}
@end
二.Swift版
// MARK: - UILabel extension
/// 这个分类为UILabel添加一些有用的方法
public extension UILabel {
/// 创建UILabel
/// - Parameters:
/// - frame: 文字坐标
/// - text: 文字内容
/// - font: 文字字体
/// - color: 文字的字体颜色
/// - alignment: 文字的对齐方式
/// - lines: 文字显示几行.
/// - shadowColor: 文字阴影(默认是没有颜色).
public convenience init(frame: CGRect, text: String, font: UIFont, color: UIColor, alignment: NSTextAlignment, lines: Int, shadowColor: UIColor = UIColor.clear) {
self.init(frame: frame)
self.font = font
self.text = text
self.backgroundColor = UIColor.clear
self.textColor = color
self.textAlignment = alignment
self.numberOfLines = lines
self.shadowColor = shadowColor
}
}