单个UITextField

时间:2016-07-04 08:11:29

标签: ios objective-c uitextfield

我有一个TextField和三个按钮,它们位于TextField上方40个点。这些按钮提供了当我点击其中任何一个时TextField文本的字体大小的更改,例如,第一个按钮设置字体大小为17秒将其更改为20,第三个将其更改为24.所以我将IbAction添加到所有按钮,如

   - (IBAction)setRegularText:(id)sender {
    self.additionalInfo.font = [UIFont systemFontOfSize:20];

}

根据按钮。但它也会改变以前输入的文本。我希望仅当用户选择该选项时才更改文本字体。以前输入的文本的字体大小不得更改。

3 个答案:

答案 0 :(得分:1)

将每个按钮的标记设置为按钮应更改的字体大小。 我是

self.button1.tag = 17;
self.button2.tag = 20;
self.button3.tag = 24;

并将标记用作字体大小。 I-E

- (IBAction)setRegularText:(UIButton *)sender {
    self.additionalInfo.font = [UIFont systemFontOfSize:sender.tag];
}

答案 1 :(得分:0)

您需要使用属性字符串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

答案 2 :(得分:0)

您可以像这样在文本字段中设置不同的文字大小:

- (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];
}