基本上我有一种方法来检查不同的位置 (newPostion),当遇到某个位置时,我将某些标签加粗,如下所示。但是,这似乎有很多代码。有一个更好的方法吗?我需要重构它以使其看起来更好,但我什至不知道从哪里开始。
if(newPosition == 100){
self.label.font = [utilClass boldFontWithSize:12];
self.label1.font = [utilClass fontWithSize:12];
self.label2.font = [utilClass fontWithSize:12];
self.label3.font = [utilClass fontWithSize:12];
self.label4.font = [utilClass fontWithSize:12];
}
else if(newPosition == 200){
self.label.font = [utilClass fontWithSize:12];
self.label1.font = [utilClass boldFontWithSize:12];
self.label2.font = [utilClass fontWithSize:12];
self.label3.font = [utilClass fontWithSize:12];
self.label4.font = [utilClass fontWithSize:12];
}
else if (newPosition == -100) {
self.label.font = [utilClass fontWithSize:12];
self.label1.font = [utilClass fontWithSize:12];
self.label2.font = [utilClass boldFontWithSize:12];
self.label3.font = [utilClass fontWithSize:12];
self.label4.font = [utilClass fontWithSize:12];
}
else (newPosition == -200) {
self.label.font = [utilClass fontWithSize:12];
self.label1.font = [utilClass fontWithSize:12];
self.label2.font = [utilClass fontWithSize:12];
self.label3.font = [utilClass boldFontWithSize:12];
self.label4.font = [utilClass fontWithSize:12];
}
最佳答案
一个解决方案可能是:
UIFont *font = [utilClass fontWithSize:12];
UIFont *bold = [utilClass boldFontSize:12];
self.label.font = font;
self.label1.font = font;
self.label2.font = font;
self.label3.font = font;
self.label4.font = font;
if (newPosition == 100) {
self.label.font = boldFont;
} else if (newPosition == 200) {
self.label1.font = boldFont;
} else if (newPosition == -100) {
self.label2.font = boldFont;
} else if (newPosition == -200) {
self.label3.font = boldFont;
}
这避免了很多冗余代码。
如果您有一组标签而不是单独的 ivar,这会变得容易得多。
NSArray *labels = @[ self.label, self.label1, self.label2, self.label3, self.label4 ];
UIFont *font = [utilClass fontWithSize:12];
UIFont *bold = [utilClass boldFontSize:12];
for (UILabel *label in labels) {
label.font = font;
}
if (newPosition == 100) {
labels[0].font = boldFont;
} else if (newPosition == 200) {
labels[1].font = boldFont;
} else if (newPosition == -100) {
labels[2].font = boldFont;
} else if (newPosition == -200) {
labels[3].font = boldFont;
}
关于iOS:我需要一种更好的方法来编写这段更改标签字体大小(粗体和常规)的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26965007/