ios - iOS 应用程序的自定义标签实现和使用

标签 ios

我在 iPhone 开发中大量使用 Storyboard。为了保持标签看起来相同,我创建了自定义 UILabels 并在自定义类中设置字体和大小。然后在 Storyboard中,我将这些类分配给 View 中显示的标签。

这工作正常,但我有 4-5 种不同类型的标签,仅尺寸或重量不同。我该如何处理这种情况?目前我有以下内容:

PrimaryLabel
PrimaryLabelBold
DescriptionLabel
DescriptionLabelSmall
DescriptionLabelBold

我认为这工作量太大,必须有更好的方法!!

最佳答案

不需要多次继承UILabel。只需创建一个子类,如下所示:

MyLabel.h

typedef NS_ENUM(NSUInteger, MyLabelStyle) {
    MyLabelStyleSmall,
    MyLabelStyleMedium,
    MyLabelStyleBig,
};

@interface MyLabel : UILabel

@property (nonatomic) MyLabelStyle style;

@end

MyLabel.m

#import "UILabel+Styles.h"

@implementation UILabel (Styles)

- (void)setStyle:(MyLabelStyle)style
{
    switch (style) {
        case MyLabelStyleSmall:
            self.font = [UIFont systemFontOfSize:12.0];
            break;
        case MyLabelStyleMedium:
            self.font = [UIFont systemFontOfSize:17.0];
            break;
        case MyLabelStyleBig:
            self.font = [UIFont systemFontOfSize:22.0];
            break;
        default:
            self.font = [UIFont systemFontOfSize:17.0];
            break;
    }
}

@end

在您的 Storyboard中,使用用户定义的运行时属性设置特定标签的样式:

enter image description here

2对应于MyLabelStyleBig。如果需要,请使用字符串而不是枚举。

关于ios - iOS 应用程序的自定义标签实现和使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24998992/

相关文章:

ios - 只有 UIButton 的中心是可点击的

IOS - 没有 "touchend"事件(非全屏 Web View )

objective-c - 如何以编程方式在 iPad 上显示导航 Controller 的下拉列表?

ios - XIB 的内容未加载

ios - 如何在 Xcode 10 中打开 Xcode 11 Beta 4 项目?

ios - 如何快速防止标签中的孤儿?

ios - .xib 中的许多 UIButton 具有不同的标签

ios - “发布”不可用 : not available in automatic reference counting mode

ios - 我如何为在 xcode 中开发的 iPhone 应用程序制作自定义应用内相机?

ios - 将 uitableview 添加到 uiview 后 didselectrowatindexpath not called ios