iOS_NSAttributedString 的21种属性详细介绍(图文混排)

(一一一)图文混排基础 -利用正则分割和拼接属性字符串 很多时候需要用到图文混排,例如聊天气泡中的表情,空间、微博中的表情,例如下图: 红心和文字在一起。 比较复杂的情况是表情夹杂在文字之间。 要实现这种功能,首先要介绍iOS中用于显示属性文字的类。 用于文字显示的类除了text属性之外,还有attributedText属性,这个属性是NSAttributedString类型,通过这个属性可以实现不同文字的不同字体、颜色甚至把图片作为文字显 阅读详情

说明:
NSAttributedString 可以非常方便的实现文字排版和图文混排功能. 共有21中效果(API), 本文将较详细的介绍21种的属性的使用

注: 本博客由@凡俊编写, @Scott, @春雨 审核, 若转载此文章,请注明出处和作者

核心API:

类: NSAttributedString, NSMutableAttributedString
API:

/**
     * API:  Character Attributes , NSAttributedString 共有21个属性
     *
     * 1. NSFontAttributeName               ->设置字体属性,默认值:字体:Helvetica(Neue) 字号:12
     *
     *
     * 2. NSParagraphStyleAttributeName     ->设置文本段落排版格式,取值为 NSParagraphStyle 对象(详情见下面的API说明)
     * 
     * 
     * 3. NSForegroundColorAttributeName    ->设置字体颜色,取值为 UIColor对象,默认值为黑色
     *
     *
     * 4. NSBackgroundColorAttributeName    ->设置字体所在区域背景颜色,取值为 UIColor对象,默认值为nil, 透明色
     * 
     *
     * 5. NSLigatureAttributeName           ->设置连体属性,取值为NSNumber 对象(整数),0 表示没有连体字符,1 表示使用默认的连体字符
     *
     *
     * 6. NSKernAttributeName               ->设置字符间距,取值为 NSNumber 对象(整数),正值间距加宽,负值间距变窄
     *
     *
     * 7. NSStrikethroughStyleAttributeName ->设置删除线,取值为 NSNumber 对象(整数)
     *
     *
     * 8. NSStrikethroughColorAttributeName ->设置删除线颜色,取值为 UIColor 对象,默认值为黑色
     *
     *
     * 9. NSUnderlineStyleAttributeName     ->设置下划线,取值为 NSNumber 对象(整数),枚举常量 NSUnderlineStyle中的值,与删除线类似
     *
     * 
     * 10. NSUnderlineColorAttributeName    ->设置下划线颜色,取值为 UIColor 对象,默认值为黑色
     *
     *
     * 11. NSStrokeWidthAttributeName       ->设置笔画宽度(粗细),取值为 NSNumber 对象(整数),负值填充效果,正值中空效果
     *
     *
     * 12. NSStrokeColorAttributeName       ->填充部分颜色,不是字体颜色,取值为 UIColor 对象
     *
     *
     * 13. NSShadowAttributeName            ->设置阴影属性,取值为 NSShadow 对象
     *
     *
     * 14. NSTextEffectAttributeName        ->设置文本特殊效果,取值为 NSString 对象,目前只有图版印刷效果可用
     *
     *
     * 15. NSBaselineOffsetAttributeName    ->设置基线偏移值,取值为 NSNumber (float),正值上偏,负值下偏
     *
     *
     * 16. NSObliquenessAttributeName       ->设置字形倾斜度,取值为 NSNumber (float),正值右倾,负值左倾
     *
     *
     * 17. NSExpansionAttributeName         ->设置文本横向拉伸属性,取值为 NSNumber (float),正值横向拉伸文本,负值横向压缩文本
     *
     *
     * 18. NSWritingDirectionAttributeName  ->设置文字书写方向,从左向右书写或者从右向左书写
     *
     *
     * 19. NSVerticalGlyphFormAttributeName ->设置文字排版方向,取值为 NSNumber 对象(整数),0 表示横排文本,1 表示竖排文本
     *
     *
     * 20. NSLinkAttributeName              ->设置链接属性,点击后调用浏览器打开指定URL地址
     *
     *
     * 21. NSAttachmentAttributeName        ->设置文本附件,取值为NSTextAttachment对象,常用于文字图片混排
     *
     */

    /**
     * API: NSParagraphStyleAttributeName
     *
     * 值为NSParagraphStyle,设置段落属性,默认值为[NSParagraphStyle defaultParagraphStyle]返回的值。
     *
     * NSMutableParagraphStyle与NSParagraphStyle包括一下属性

     * alignment                ->对齐方式
     * firstLineHeadIndent      ->首行缩进
     * headIndent               ->缩进
     * tailIndent               ->尾部缩进
     * lineBreakMode            ->断行方式
     * maximumLineHeight        ->最大行高
     * minimumLineHeight        ->最低行高
     * lineSpacing              ->行距
     * paragraphSpacing         ->段距
     * paragraphSpacingBefore   ->段首空间
     * baseWritingDirection     ->句子方向
     * lineHeightMultiple       ->可变行高,乘因数。
     * hyphenationFactor        ->连字符属性
     */

代码

- (void)creatTitleLabel {

    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 320, 400)];
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.layer.borderColor = [UIColor grayColor].CGColor;
    self.titleLabel.layer.borderWidth = 0.5;
    self.titleLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:self.titleLabel];

    NSString *string = @"An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string. ";

    /* 这句话就是对这个类的一个最简明扼要的概括。NSAttributedString管理一个字符串,以及与该字符串中的单个字符或某些范围的字符串相关的属性。它有一个子类NSMutableAttributedString
     * 具体实现时,NSAttributedString维护了一个NSString,用来保存最原始的字符串,另有一个NSDictionary用来保存各个子串/字符的属性。
     */


#pragma mark - NSMutableAttributedString 创建
    /* 三种初始化方法,NSMutableAttributedString没有初始化方法,使用父类初始化方法, 使用initWithString:, initWithString:attributes:, 或者 initWithAttributedString: */
    NSAttributedString *attStri = [[NSAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:30]}];

    NSMutableAttributedString *mAttStri = [[NSMutableAttributedString alloc] initWithString:string];


#pragma mark ** 1. NSFontAttributeName 设置字体属性
    /* 字体大小 及 字体类型 */
    NSRange font_range = [string rangeOfString:@"An"];
    [mAttStri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:font_range];
    [mAttStri addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:17.0] range:NSMakeRange(10, 10)];


#pragma mark ** 2. NSParagraphStyleAttributeName 设置文本段落排版格式
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.firstLineHeadIndent = 20;
    style.lineSpacing = 10;

    [mAttStri addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, mAttStri.length / 2)];

#pragma mark ** 3. NSForegroundColorAttributeName 设置字体颜色
    /* 值为UIColor,字体颜色,默认为黑色. */
    [mAttStri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, mAttStri.length)];


#pragma mark ** 4. NSBackgroundColorAttributeName 设置字体所在区域背景颜色
    /* 值为UIColor,字体背景色,默认透明. */
    [mAttStri addAttribute:NSBackgroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, 20)];


#pragma mark ** 5. NSLigatureAttributeName 设置连体属性
    /* 取值为NSNumber 对象(整数). 0 表示没有连体字符, 1 表示使用默认的连体字符. 一般中文用不到,在英文中可能出现相邻字母连笔的情况 */
    [mAttStri addAttribute:NSLigatureAttributeName value:@0 range:NSMakeRange(0, mAttStri.length)];



#pragma mark ** 6. NSKernAttributeName 设置字符间距
    /* 值为浮点数NSNumber,字距属性,默认值为0。*/
    [mAttStri addAttribute:NSKernAttributeName value:@3 range:NSMakeRange(0, mAttStri.length)];



#pragma mark ** 7. NSStrikethroughStyleAttributeName 设置删除线
    /* 值为整型NSNumber,可取值为
        enum {

        NSUnderlineStyleNone = 0×00,

        NSUnderlineStyleSingle = 0×01,

        }; 设置删除线。
    */
    [mAttStri addAttribute:NSStrikethroughStyleAttributeName value:@3 range:NSMakeRange(3, 7)];


#pragma mark ** 8. NSStrikethroughColorAttributeName 设置删除线颜色
    /* 这个属性的值是一个UIColor对象. */
    [mAttStri addAttribute:NSStrikethroughColorAttributeName value:[UIColor blueColor] range:NSMakeRange(3, 3)];


#pragma mark ** 9. NSUnderlineStyleAttributeName 设置下划线
    /* 取值为 NSNumber 对象(整数),枚举常量 NSUnderlineStyle中的值,与删除线类似 */
    [mAttStri addAttribute:NSUnderlineStyleAttributeName value:@2 range:NSMakeRange(6, 5)];


#pragma mark ** 10. NSUnderlineColorAttributeName 设置下划线颜色
    /* 这个属性的值是一个UIColor对象.默认值为nil. */
    [mAttStri addAttribute:NSUnderlineColorAttributeName value:[UIColor blackColor] range:NSMakeRange(6, 5)];



#pragma mark ** 11. NSStrokeWidthAttributeName 设置笔画宽度(粗细)
    /* 值为浮点数NSNumber。设置笔画的粗细。负值填充效果,正值中空效果. */
    [mAttStri addAttribute:NSStrokeWidthAttributeName value:@10 range:NSMakeRange(50, 30)];


#pragma mark ** 12. NSStrokeColorAttributeName 填充部分颜色,
    /* 不是字体颜色,取值为 UIColor 对象 默认值为nil,设置的属性同ForegroundColor。*/
    [mAttStri addAttribute:NSStrokeColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(50, 20)];


#pragma mark ** 13. NSShadowAttributeName 设置阴影属性

    /* 值为NSShadow,设置笔画的阴影,默认值为nil。*/
    NSShadow *shadow = [[NSShadow alloc]init];
    shadow.shadowOffset = CGSizeMake(10, 10);
    shadow.shadowColor = [UIColor greenColor];
    [mAttStri addAttribute:NSShadowAttributeName value:shadow range:NSMakeRange(20, 10)];


#pragma mark ** 14. NSTextEffectAttributeName 设置文本特殊效果
    /* 这个属性的值是一个NSString对象。使用此属性指定的文字效果,如NSTextEffectLetterpressStyle。此属性的默认值为nil,表示没有文本效应。*/
    [mAttStri addAttribute:NSTextEffectAttributeName value:NSTextEffectLetterpressStyle range:NSMakeRange(80, 10)];



#pragma mark ** 15. NSBaselineOffsetAttributeName 设置基线偏移值
    /* 此属性的值是包含一个浮点值的NSNumber对象,表示的字符从基线偏移的NSNumber对象,默认值是0。正值上偏,负值下偏 */
    [mAttStri addAttribute:NSBaselineOffsetAttributeName value:@5 range:NSMakeRange(112, 10)];


#pragma mark ** 16. NSObliquenessAttributeName 设置字形倾斜度取值为 NSNumber (float),正值右倾,负值左倾
    /* 此属性的值是包含一个浮点值的NSNumber对象。默认值为0,表示没有倾斜, 正值右倾,负值左倾。 */
    [mAttStri addAttribute:NSObliquenessAttributeName value:@0.8 range:NSMakeRange(135, 15)];


#pragma mark ** 17. NSExpansionAttributeName 设置文本横向拉伸属性
    /* 取值为 NSNumber(float), 正值横向拉伸文本, 负值横向压缩文本 */
    NSRange range =  [string rangeOfString:@"An association of"];
    [mAttStri addAttribute:NSExpansionAttributeName value:@1.0 range:range];



#pragma mark ** 18. NSWritingDirectionAttributeName 设置文字书写方向
    /** 
     * 取值为包含NSNumber对象的数组. 从左向右书写或者从右向左书写.
     *
     * The values of the NSNumber objects should be 0, 1, 2, or 3, for LRE, RLE, LRO, or RLO respectively, and combinations of NSWritingDirectionLeftToRight and NSWritingDirectionRightToLeft with NSTextWritingDirectionEmbedding or NSTextWritingDirectionOverride, as shown in Values of NSWritingDirectionAttributeName and equivalent markup.

     */
    NSRange rang2 = [string rangeOfString:@"characters and their"];
    [mAttStri addAttribute:NSWritingDirectionAttributeName value:@[@3] range:rang2];



#pragma mark ** 19. NSVerticalGlyphFormAttributeName 设置文字排版方向
    /**
     * 值为整型NSNumber,0为水平排版的字,1为垂直排版的字。注意,在iOS中, 总是以横向排版
     *
     * In iOS, horizontal text is always used and specifying a different value is undefined.
     */
    [mAttStri addAttribute:NSVerticalGlyphFormAttributeName value:@1 range:NSMakeRange(1, 10)];



#pragma mark ** 20. NSLinkAttributeName 设置链接属性
    /**
     * 此属性的值是NSURL对象(首选)或一个NSString对象。此属性的默认值为nil,表示没有链接。
     * UILabel无法使用该属性, 可以使用UITextView 控件.
     */
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 450, 320, 60)];
    [self.view addSubview:textView];
    textView.backgroundColor  = [UIColor lightGrayColor];


    NSString *strLink = @"百度链接";
    NSAttributedString *attStr  = [[NSAttributedString alloc] initWithString:strLink attributes:@{NSLinkAttributeName: [NSURL URLWithString:@"http://www.baidu.com"]}];

    textView.editable = NO;

    /* 签订协议, 指定代理人之后. 但点击链接时, 会回调协议方法 (- textView:shouldInteractWithURL:inRange:) */
    textView.delegate = self;

    textView.attributedText = attStr;


#pragma mark ** 21. NSAttachmentAttributeName 设置文本附件
    /* 这个属性的值是一个NSTextAttachment对象。此属性的默认值为nil,表示无附件。*/

    /**
     * 关于NSTextAttachment类的简单说明
     *
     * NSTextAttachment 类有一个指定的初始化方法(- initWithData:ofType:), 需要指定附件文档的数据和附件文件的类型. 如果附件文档数据指定nil, 那么系统将会默认指定为image对象作为值. 因此, 也可以通过这个特性实现图文混排.
     * 下面就以附件为image对象来说明NSAttachmentAttributeName的使用.
     *
     */

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 550, 320, 60)];
    label.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:label];


    /* 下面实现在百度两个汉字之间插入一个照片 */
    NSString *stiAtt = @"百度";

    NSTextAttachment *attach = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
    attach.bounds = CGRectMake(0, 0, 50, 50);
    attach.image = [UIImage imageNamed:@"baidu.jpg"];

    NSAttributedString *strAtt = [NSAttributedString attributedStringWithAttachment:attach];

    NSMutableAttributedString *strMatt = [[NSMutableAttributedString alloc] initWithString:stiAtt];

    [strMatt insertAttributedString:strAtt atIndex:1];

    label.attributedText = strMatt;

    self.titleLabel.attributedText = mAttStri;
    [self.titleLabel sizeToFit];

}


#pragma mark - textView delegate 
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {

    NSLog(@"%s", __func__);
    NSLog(@"url: %@", URL);
    return YES;
}

Demo的链接地址

iOS Label的图文混排 最近做项目,要达到一个效果,图片加文字,文字是从后台获取的数据,长度不确定,但是要求图片文字挨着(imageView.right 和 label.leading相等),本人技术欠缺,所以刚开始实现的效果是这样的。如图 为了达到效果,所以想了 几个方法‘ 1:请求完数据,然后计算数据的长度,然后把 这行UI 重新写一下 网上找的别人的,还没试验过 下面分两种情况考虑: 1、UILa 阅读详情

相关推荐

iOS开发实战:图文混排实现详解

iOS图文混排是现代App开发中实现富文本展示的核心技术之一。随着用户对界面美观度和信息表达方式要求的提升,传统的纯文本展示已无法满足需求。图文混排不仅可以增强内容的表现力,还能提升用户的阅读体验。本章将介绍图文混排的基本概念、应用场景以及其在iOS开发中的重要性。通过理解图文混排的实现原理和使用场景,开发者可以更好地掌握后续章节中关于Core Text框架的深入内容,为构建高性能、高自由度的富文本展示组件打下坚实的理论基础。

weixin_33816734的博客 1103

iOS NSAttributedString所有文本属性详解(多图)

转自 http://blog.youkuaiyun.com/hello_hwc/article/details/46731991  前言:这篇文章算是整理吧,因为最近逛Stackoverflow的时候,发现自己这部分掌握的不是很好。 一个简单的例子 绘制不同颜色不同字体的一个AttributeString,如图    代码 UILabel * Label = [[UILa

Lw_Chen的博客 1579

Unity坦克物理系统:履带驱动与力场建模实战指南

在游戏物理仿真中,履带车辆的运动建模远超传统轮式控制器的范畴。其核心在于摒弃WheelCollider的滚动幻觉,转向基于牛顿力学的力与力矩协同求解——通过主推进力场、转向力矩场和地面反作用力场三重叠加,实现对质量、摩擦、惯性及坡度阻力的真实响应。这种建模方式不仅支撑坦克爬坡、陷泥、侧倾等复杂行为,更保障了多人同步与高帧率下的物理稳定性。Physics Tank Maker 正是这一思路的工业级落地,它将PhysX底层机制与坦克动力学深度耦合,提供可调参数、事件驱动视觉反馈及标准扩展接口,成为面向严肃模拟类

weixin_29535577的博客 562

图文混排之NSAttributedString(超级详细的富文本大全)

图文混排之NSAttributedString(超级详细的富文本大全)

vkooy的博客 1379

Ubuntu 20.04 + CARLA 0.9.13 长时运行崩溃?手把手教你定位和缓解Segmentation fault

本文详细解析了Ubuntu 20.04环境下CARLA 0.9.13仿真平台长时运行崩溃问题,提供了从内存监控到核心转储分析的系统级诊断方法,并分享内存泄漏缓解、稳定性优化配置等实用解决方案,帮助开发者构建更稳定的自动驾驶仿真环境。

weixin_28362173的博客 253

Verilog实现SPI通信协议驱动设计

线性序列机实现SPI协议

H19981118的博客 6085

UILable属性详解,设置居上对齐,居中对齐,居下对齐,获取斜体字,字体、大小、单位、颜色

原文地址:http://segmentfault.com/a/1190000003491677 ·常用属性和方法有: 1、创建 CGRect rect = CGRectMake(100, 200, 50, 50); UILabel *label = [[UILabel alloc] initWithFrame:rect]; 2、text //设置和读取文本内容,默认为nil label.

3648

运用AD进行stm32最小系统PCB图的绘制

运用AD进行stm32最小系统PCB图的绘制一、PCB图的绘制(1)布局(2)布线(3)覆铜(4)电气规则检查二、给PCB添加logo三、生成garber文件总结 一、PCB图的绘制 (1)布局 1.画好原理图后,新建一个PCB项目 2.在Design中选择第二项,导入器件 3.先点击右下角第一项,再点第二项导入器件 导入成功 4.导入后效果 选择紫红色方框,按电脑上的delete键把它删掉 5.在Tools选择Outside Board,自动排布器件 排布后效果如图 6.画线,确定板子范围

lucario1的博客 2149

富文本

ios项目中经常需要显示一些带有特殊样式的文本,比如说带有下划线、删除线、斜体、空心字体、背景色、阴影以及图文混排(一种文字中夹杂图片的显示效果)。通常想要实现这些效果要使用到iOS的Foundation框架提供的NSAttributedString类,NSAttributedString类中有许多属性,不同属性对应不同的文本样式。本文主要对这些属性做一个解释说明,并会结合实际代码来应用它们。 ...

雨夜枫起的博客 914

用5毫欧采样电阻实现高精度电流检测?数字可调电源控制板的硬件设计陷阱

本文深入探讨了在数字可调电源控制板设计中,如何利用5毫欧采样电阻实现高精度电流检测。从微小信号放大电路设计、采样电阻布局与热管理,到电源切换与电池管理电路优化,提供了全面的硬件设计解决方案和实用技巧,帮助工程师规避常见设计陷阱,提升系统性能。

wdx0123456的博客 1029

实用工具抓取youtube热门数据

YouTube作为全球第二大搜索引擎,2024年日均视频播放量突破50亿次,头部创作者单月广告分成可达百万美元量级。但对数据分析者而言,其反爬机制堪称业界最严: ‌反爬技术升级‌:Google部署的Botguard系统可检测异常流量,触发机制包括: 单IP每小时请求超过50次即封禁 检测Headless浏览器指纹(如Chrome的navigator.webdriver属性) 动态加载内容(如评论数据需滚动页面3次后加载) ‌数据价值维度‌:某MCN机构研究显示,前100热门视频的标题关键词复用率高达67%

26万+

NSAttributedString装载图片与UIImageView装载图片对比

一、先简单介绍一下NSAttributedString如何装载图片: NSAttributedString有一个类方法attributedStringWithAttachment:参数是NSTextAttachment,NSTextAttachment有一个叫做image的属性。所以自然就可以将一张图片插入到NSAttributedString中然后赋值给UILabel的attributedTex

NunchakusHuang的专栏 5189

Ansys Zemax实战:5步搞定多模光纤耦合效率优化(附IMAE操作数详解)

本文详细介绍了使用Ansys Zemax优化多模光纤耦合效率的5个关键步骤,包括几何图像分析设置、IMAE操作数应用及偏振效应处理。通过实战案例解析,帮助工程师快速掌握光纤耦合效率提升技巧,特别针对IMAE操作数的配置保存机制和菲涅尔损耗控制进行深度讲解。

potato的博客 690

slate富文本转html,textView富文本AttributedString,转换成html

WebView虽然也可以实现图文混排的效果,但是在使用的时候比较复杂,而且WebVIew的内存泄漏相当明显,使用不好反而得补偿失。现在很多的新闻类App都采用自己写的富文本进行图文混排。下载已经封装好的富文本标签类RCLabel(http://www.okbase.net/file/item/20694)该类是由一牛人封装好的用于实现图文混排的富文本类,在下载下来的源代码中可以看到其用法,但是这里...

weixin_42129005的博客 668

C#实现将DataGridView中数据导出到Excel (附完整源码)

C#实现将DataGridView中数据导出到Excel (附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 1589

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

iOS--NSAttributedString超全属性详解及应用(富文本、图文混排)

ios项目中经常需要显示一些带有特殊样式的文本,比如说带有下划线、删除线、斜体、空心字体、背景色、阴影以及图文混排(一种文字中夹杂图片的显示效果)。通常想要实现这些效果要使用到iOS的Foundation框架提供的NSAttributedString类,NSAttributedString类中有许多属性,不同属性对应不同的文本样式。本文主要对这些属性做一个解释说明,并会结合实际代码来应用它们。 ...

小天空的博客 3910

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

ios图文混排简单演示

本人做ios开发有些时间了,由于工作忙和自己懒得写,所以一直没有写过技术博客,今日突发奇想,还是写点东西吧,分享给大家。好今天我简单介绍下ios开发中图文混排的一些内容.     图文混排呢说直白点就是图片和文字排在一起,ios中常用的一些控件都可以进行图文混排,比如UIButton、UIlabel、UITextView等等很多,我们只需要设置它们的 attributedText就可以了,比如

Think_lion的博客 1704

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

NSAttributedString,简单图文混排,UITextKit

图文混排一般都会用CoreText来实现,单对于初学者来说,却不是那么容易能够接受,所以我在这里分享一下简单的实现方法。 最终可以实现 如下的效果。 注:这里的实现并未用到CoreText, 而用到了TextKit里的NSAttributedString和NSTextAttachment 一、小试牛刀: //1.先创建 NSMutableAttributedString, N

stree7cleaner的博客 1003

图文混排的四种方案

转载自:http://lemon2well.top/2018/08/15/iOS%20开发/图文混排的四种方案/ 图文混排有多种方式可以实现,下面我会用四种不同的方式来实现以下界面的效果,并且说明他们的优缺点。 NSAttributedString NSAttributedString提供了自由并且多样式的富文本设置,图文混排的实现是通过插入NSTestAttachment来实现。 talk is cheap ,here is the code 1 2 3 4 5 6 7 .

沸腾的泪水的专栏 4057

NSAttributedString实现图文混排

NSMutableAttributedString富文本 在iOS开发中,常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求。以及一些直播界面中包含图片和字体的弹幕效果,大部分都是由NSMuttableAttstring(带属性的字符串)实现的。 一、简易使用方法 1、示例代码 fileprivate func addAttributeString() -> NS

RunningKing 945

ios 解析html图文混排,iOS 之 图文混排(富文本)

学习自MJ,分享给大家!分类// 富文本技术:// 1.图文混排// 2.随意修改文字样式与CoreText,textKit的区别/**iOS 6之前:CoreText,纯C语言,极其蛋疼iOS 6开始:NSAttributedString,简单易用iOS 7开始:TextKit,功能强大,简单易用*/代码示例及注释讲解- (void)setupTextView{// 富文本技术:// 1.图文混...

weixin_36210213的博客 603

IOS图文混排

在iOS6之前,苹果系统的图文混排技术使用coreText:如果需要使用可以使用第三方框架(纯C语言) iOS6使用NSAttributedString、NSMutableAttributedString iOS7 使用textKit 方法一: NSMutableAttributedString *string = [[NSMutableAttributedSt

Zjl的博客 593

用NSAttributedString实现简单的图文混排-----(确实几个需要注意的地方都注意到了就好了。)

iOS7以后,因为TextKit的强大,可以用NSAttributedString很方便的实现图文混排(主要是利用了NSTextAttachment)。 关于Textkit的牛逼之处,可以参考objcio上的文章(https://objccn.io/issue-5-1/) 我用NSAttributedString仿写了一个知乎的输入框(低仿,就是有个功能而已),效果如图:

春风得意,马蹄仍急;少年豪情,一笑难回。 1641

iOS-NSAttributedString自定义文字变色

1.使用注意: 1.给UILabel设置attributedText了会导致给UILabel中text,font,textColor,shadowColor,shadowOffset,textAlignment,lineBreakMode这7个属性设置值时无效果。 2.这个框架的应用场景一般在图文混排和搜索功能中应用比较多。 2.需求:让文本标签文字部分变色 2.1.示例代码如下: #i...

aiqiangli4321的博客 428

iOS图文混排

自定义NSAttributedString分类// NSAttributedString+Additon.h #import <UIKit/UIKit.h>@interface NSAttributedString (Additon)/// 使用图像和文本生成上下排列的属性文本 /// /// @param image 图像 /// @param imageWH 图像宽高 ///

Zok93 1579
上一篇: iOS_CoreFoundation_汉字转换拼音的实现
下一篇: iOS_ NSUserDefaults_数据本地化的轻型装备
CaoYuan_CIKU
博客等级 码龄11年 40粉丝 58原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值