UITextView设置文字垂直居中和LinkAttribute

本文介绍如何使用Swift通过设置NSAttributedString的属性来实现UITextView中文字的垂直居中对齐及可点击链接文本。文中提供了具体的代码实现示例,包括设置段落样式、字体大小颜色等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

UITextView设置文字垂直居中和LinkAttribute

想要几行文字居中对齐的实现方式有多种,如使用:UILabel,UITextField,UITextView。以下是UITextView的简单使用。

    NSMutableDictionary *ornamentAttributes = [NSMutableDictionary dictionary];
    NSMutableParagraphStyle *ornamentParagraph = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    //设置text文字垂直居中
    ornamentParagraph.alignment = NSTextAlignmentCenter;
    //设置行间距
    ornamentParagraph.lineSpacing = 5;
    ornamentAttributes[NSParagraphStyleAttributeName] = ornamentParagraph;
    //整个字符串的样式
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:17],NSParagraphStyleAttributeName: ornamentParagraph, NSForegroundColorAttributeName: UIColorFromRGB(0x7dd4f2)};

    //设置可点击字符串的Attributes
    NSDictionary *linkAttributes = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle], NSLinkAttributeName: @"1", NSForegroundColorAttributeName: [UIColor whiteColor]};

    //初始化字符串
    NSMutableAttributedString *content = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"注册使用XXXXX,就表示您同意\nXXXXX的用户协议"] attributes: attributes];
    [content addAttributes:linkAttributes range: NSMakeRange(content.length - 4, 4)];

    self.textView.editable = NO;
    self.textView.linkTextAttributes = linkAttributes;
    self.textView.delegate = self;//设置UITextView的代理为self
    self.textView.attributedText = content;
    self.textView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_textView];

实现UITextViewDelegate的代理方法:
- (BOOL) textView:(UITextView )textView shouldInteractWithURL:(NSURL )URL inRange:(NSRange)characterRange

- (BOOL) textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    ...
    ...
    do some thing;
    ...
    ...
    return YES;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值