【问题标题】:Make text underlined in xcode在 xcode 中为文本添加下划线
【发布时间】:2012-09-07 13:47:45
【问题描述】:

嘿,我正在制作一个需要在文本视图文本的特定部分加下划线的应用。有没有一种简单的方法可以让它变成粗体和斜体,或者我必须制作和导入自定义字体?提前感谢您的帮助!

【问题讨论】:

    标签: uitextfield underline


    【解决方案1】:
    #import <UIKit/UIKit.h>
    
    @interface TextFieldWithUnderLine : UITextField
    
    @end
    
    #import "TextFieldWithUnderLine.h"
    
    @implementation TextFieldWithUnderLine
    
    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            // Initialization code
        }
        return self;
    }
    
    - (void)drawRect:(CGRect)rect {
    
        //Get the current drawing context
        CGContextRef context = UIGraphicsGetCurrentContext();
        //Set the line color and width
        CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
        CGContextSetLineWidth(context, 0.5f);
        //Start a new Path
        CGContextBeginPath(context);
    
        // offset lines up - we are adding offset to font.leading so that line is drawn right below the characters and still characters are visible.
        CGContextMoveToPoint(context, self.bounds.origin.x, self.font.leading + 4.0f);
        CGContextAddLineToPoint(context, self.bounds.size.width, self.font.leading + 4.0f);
    
        //Close our Path and Stroke (draw) it
        CGContextClosePath(context);
        CGContextStrokePath(context);
    }
    
    @end
    

    【讨论】:

      【解决方案2】:

      这就是我所做的。它就像黄油一样工作。

      1) 将CoreText.framework 添加到您的框架中。

      2) 在需要下划线标签的类中导入&lt;CoreText/CoreText.h&gt;

      3) 编写以下代码。

      NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"My Messages"];
      [attString addAttribute:(NSString*)kCTUnderlineStyleAttributeName
                        value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
                        range:(NSRange){0,[attString length]}];
      self.myMsgLBL.attributedText = attString;
      self.myMsgLBL.textColor = [UIColor whiteColor];
      

      【讨论】:

        【解决方案3】:

        从 iOS 6.0 开始,UILabelUITextFieldUITextView 支持使用属性文本属性显示 attributed strings

        用法:

        NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc] initWithString:@"text"];
        [aStr addAttribute:NSUnderlineStyleAttributeName value:NSUnderlineStyleSingle range:NSMakeRange(0,2)];
        label.attributedText = aStr;
        

        【讨论】:

        • 有些事情没有解决;这是我的代码你看到有什么明显的错误吗? NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc] initWithString:BookTitle.text]; [aStr addAttribute:NSUnderlineStyleAttributeName 值:NSUnderlineStyleSingle 范围:NSMakeRange(0,2)]; BookTitle.attributedText = aStr;
        • BookTitle 是一个文本字段
        猜你喜欢
        • 2012-09-15
        • 1970-01-01
        • 2012-04-18
        • 2015-03-04
        • 2011-04-13
        • 1970-01-01
        • 1970-01-01
        • 2013-02-21
        • 2015-05-29
        相关资源
        最近更新 更多