8

次のコードを使用して、iOS 8でNSAttributedStringforを生成しています。UILabel

// a long long Chinese title 
NSString *title = @"这是一个很长很长很长很长很长很长的中文标题";
// setup icon attachment
NSTextAttachment *iconAttachment = [[NSTextAttachment alloc] init];
iconAttachment.image = [UIImage imageNamed:imageName];
iconAttachment.bounds = bounds;
NSAttributedString *ycardImageString = [NSAttributedString attributedStringWithAttachment:iconAttachment];

// setup attributed text
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:title];
if (shouldShowYcard) {
    [attributedText insertAttributedString:ycardImageString atIndex:0];
    [attributedText insertAttributedString:[[NSAttributedString alloc] initWithString:@" "] atIndex:1];
    [attributedText addAttribute:NSBaselineOffsetAttributeName value:@(offset) range:NSMakeRange(0, 1)];
}
NSRange titleRange = NSMakeRange(shouldShowYcard ? 2 : 0, title.length);
[attributedText addAttribute:NSFontAttributeName value:font range:titleRange];
[attributedText addAttribute:NSForegroundColorAttributeName value:color range:titleRange];

ただしNSTextAttachment、次の写真のように、切り捨てられた尾の垂直位置に影響するようです。

NSTextAttachment を使用した NSAttributedString NSTextAttachment のない NSAttributedString 英語の NSTextAttachment を含む NSAttributedString 英語で NSTextAttachment のない NSAttributedString

切り捨てられた尾の垂直方向の調整を設定する方法はありますか?

私の目標は、中国語でテールを下揃えにすることです。

テスト用のアイコンです。アイコン

4

3 に答える 3

4

これを試してみてください

   UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(50, 300, 300, 30)];
    [self.view addSubview:lbl];
    NSString *t= @"这是一个很长很长很长很长很长很长的中文标题漢字";
    NSTextAttachment *iconatt = [[NSTextAttachment alloc]init];
    iconatt.image = [UIImage imageNamed:@"phnzY.png"];
    iconatt.bounds = CGRectMake(0, 0, 44, 22);

    NSAttributedString *ycardstring = [NSAttributedString attributedStringWithAttachment:iconatt];
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:t];
    [attributedText insertAttributedString:ycardstring atIndex:0];
    [attributedText insertAttributedString:[[NSAttributedString alloc] initWithString:@" "] atIndex:1];
     [attributedText addAttribute:NSBaselineOffsetAttributeName value:@(0.0) range:NSMakeRange(0, 1)];
        NSRange titleRange = NSMakeRange( 0 , t.length);
    [attributedText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22.0] range:titleRange];
    [attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:titleRange];
    lbl.attributedText = attributedText;

このような出力が得られます

出力

于 2016-10-18T10:15:20.773 に答える