美文网首页
iOS Button.setAttributedTitle或者U

iOS Button.setAttributedTitle或者U

作者: Dove_iOS | 来源:发表于2019-03-26 17:18 被阅读0次

前言:
attributedText之坑
不管怎么设置文本格式,都不居中,是左对齐

原因:
在设置attributedText富文本的时候将忽略下列基础设置:

       @property(nullable, nonatomic,copy)   NSString           *text;            // default is nil

       @property(null_resettable, nonatomic,strong) UIFont      *font;            // default is nil (system font 17 plain)

       @property(null_resettable, nonatomic,strong) UIColor     *textColor;       // default is nil (text draws black)

       @property(nullable, nonatomic,strong) UIColor            *shadowColor;     // default is nil (no shadow)

       @property(nonatomic)        CGSize             shadowOffset;    // default is CGSizeMake(0, -1) -- a top shadow

       @property(nonatomic)        NSTextAlignment    textAlignment;   // default is NSTextAlignmentLeft

       @property(nonatomic)        NSLineBreakMode    lineBreakMode;   // default is NSLineBreakByTruncatingTail. used for single and multiple lines of text

解决办法:
在函数中恢复设置,代码如下:

  //行间距,对齐模式,高亮字体颜色(editTextColor自定义的),还可以加link等....
   func stringAttribute(string: String, attributeSting: String, attributeTextColor: UIColor = UIColor.editTextColor(), alignment: NSTextAlignment = .left, size: CGFloat = 14) -> NSAttributedString {
    let contentStr = string as NSString
    let str : NSMutableAttributedString = NSMutableAttributedString(string:contentStr as String)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 6//行间距
    paragraphStyle.alignment = alignment//对齐模式
    str.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, contentStr.length))
    let range = contentStr.range(of: attributeSting, options: .regularExpression, range: NSMakeRange(0, contentStr.length))
    let myAttribute = [NSAttributedStringKey.foregroundColor: attributeTextColor,
                       NSAttributedStringKey.font: UIFont.systemFont(ofSize: size)] as [NSAttributedStringKey : Any]
    str.addAttributes(myAttribute, range: range)
    return str
}

 (button.titleLabel?).numberOfLines = 0不要忘记

使用方法:

   //为某一范围内文字设置多个属性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

   //为某一范围内文字添加某个属性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

   //为某一范围内文字添加多个属性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;

   //移除某范围内的某个属性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;

常见的属性及说明

   NSFontAttributeName //字体

   NSParagraphStyleAttributeName  //段落格式 

   NSForegroundColorAttributeName  //字体颜色

   NSBackgroundColorAttributeName  //背景颜色

   NSStrikethroughStyleAttributeName  //删除线格式

   NSUnderlineStyleAttributeName  //下划线格式

   NSStrokeColorAttributeName  //删除线颜色

   NSStrokeWidthAttributeName  //删除线宽度

   NSShadowAttributeName  //阴影

相关文章

网友评论

      本文标题:iOS Button.setAttributedTitle或者U

      本文链接:https://www.haomeiwen.com/subject/kqrnvqtx.html