【问题标题】:Multiple fonts inside a single UITextField单个 UITextField 中的多种字体
【发布时间】:2016-07-04 08:11:28
【问题描述】:
我有一个 TextField 和三个按钮,它们位于 TextField 上方 40pts。当我单击其中任何一个按钮时,这些按钮提供了 TextField 文本字体大小的更改,例如,第一个按钮将字体大小设置为 17,第二个将其更改为 20,第三个将其更改为 24。所以我将 IbAction 添加到所有按钮,例如
- (IBAction)setRegularText:(id)sender {
self.additionalInfo.font = [UIFont systemFontOfSize:20];
}
并按按钮。但它也会改变之前输入的文本。我希望仅在用户选择该选项时更改文本字体。不得更改以前输入的文本的字体大小。
【问题讨论】:
标签:
ios
objective-c
uitextfield
【解决方案1】:
将每个按钮的标签设置为该按钮应更改的字体大小。
即
self.button1.tag = 17;
self.button2.tag = 20;
self.button3.tag = 24;
并使用标签作为字体大小。
即
- (IBAction)setRegularText:(UIButton *)sender {
self.additionalInfo.font = [UIFont systemFontOfSize:sender.tag];
}
【解决方案2】:
您将需要使用属性字符串NSAttributedString。对于文本字段,最好有一个委托并实现更改范围内字符的方法。即使用户从其他地方粘贴文本,这也将处理所有情况。
所以NSMutableAttributedString 有一种方法可以用可变属性字符串替换范围内的字符串,该方法非常适合此方法。代理接收到的新字符串必须简单地转换为具有当前设置字体的属性字符串。
试试这样的:
@interface AttributedTextField : NSObject<UITextFieldDelegate>
@property (nonatomic, strong) NSMutableAttributedString *attributedString;
@property (nonatomic, strong) UIFont *currentFont;
@end
@implementation AttributedTextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// ensure having a font
UIFont *font = self.currentFont;
if(font == nil) {
font = [UIFont systemFontOfSize:12.0f];
}
// ensure having a base string
if(self.attributedString == nil) {
self.attributedString = [[NSMutableAttributedString alloc] initWithString:@""];
}
// append the new string
[self.attributedString replaceCharactersInRange:range withAttributedString:[[NSMutableAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName: font}]];
textField.attributedText = self.attributedString; // assign the new text which is attributed
return NO; // return false as we are overriding the text
}
@end
【解决方案3】:
您可以像这样在文本字段中设置不同的文本大小:
- (void)setFontString:(NSString *)setString setFontSize: (double) fontSize {
self.txtAnswer.text = @"";
self.txtAnswer.text = setString;
self.txtAnswer.font = [UIFont systemFontOfSize:fontSize];
}
- (IBAction)btn1Tap:(id)sender {
[self setFontString:@"Good Morning" setFontSize:20.0f];
}
- (IBAction)btn2Tap:(id)sender {
[self setFontString:@"Good Afternoon" setFontSize:15.0f];
}
- (IBAction)btn3Tap:(id)sender {
[self setFontString:@"Good Evening" setFontSize:10.0f];
}