• 让UILabel的文字顶部对齐


    参考资料

    http://stackoverflow.com/questions/1054558/how-do-i-vertically-align-text-within-a-uilabel 

    方法一

    在显示文字时,首先计算显示当前的文字需要多宽和多高,然后将对应的UILabel的大小改变成对应的宽度和高度。此方法的相示意图如下:

    在显示文字时,首先计算显示当前的文字需要多宽和多高,然后将对应的UILabel的大小改变成对应的宽度和高度。此方法的相示意图如下:

    CGSize maximumSize = CGSizeMake(300, 9999);
    NSString *dateString = @"The date today is January 1st, 1999";
    UIFont *dateFont = [UIFont fontWithName:@"Helvetica" size:14];
    CGSize dateStringSize = [dateString sizeWithFont:dateFont
    constrainedToSize:maximumSize
    lineBreakMode:self.dateLabel.lineBreakMode];
    CGRect dateFrame = CGRectMake(10, 10, 300, dateStringSize.height);
    self.dateLabel.frame = dateFrame;

    方法二

    此方法更加简单粗暴,但是很有效。其方法是在文本后面加多一些 。
    需要注意的是, 后还得加至少一个空格,否则多余的 会被UILabel忽略。从这一点上看,UILabel似乎又过于“聪明”了。

    该方法的示意图如下:

    该方法的代码如下:

    for(int i=0; i<newLinesToPad; i++)
    self.text = [self.text stringByAppendingString:@" "];

    方法三

    最正统的方法,利用objective-c的category特性,修改UILabel的绘制代码。示例代码如下:

    // -- file: UILabel+VerticalAlign.h
    #pragma mark VerticalAlign
    @interface UILabel (VerticalAlign)
    - (void)alignTop;
    - (void)alignBottom;
    @end

    // -- file: UILabel+VerticalAlign.m
    @implementation UILabel (VerticalAlign)
    - (void)alignTop {
    CGSize fontSize = [self.text sizeWithFont:self.font];
    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width; //expected width of label
    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
    int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
    for(int i=0; i<newLinesToPad; i++)
    self.text = [self.text stringByAppendingString:@" "];
    }

    - (void)alignBottom {
    CGSize fontSize = [self.text sizeWithFont:self.font];
    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width; //expected width of label
    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
    int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
    for(int i=0; i<newLinesToPad; i++)
    self.text = [NSString stringWithFormat:@" %@",self.text];
    }
    @end
  • 相关阅读:
    8-16 不无聊序列 non-boring sequences uva1608
    8-8 Ddfense Line uva1471 优先级队列
    8-12 Erratic Expansion uva12627
    8-4 Fabled Rooks uva11134
    8-10 Coping Books uva714
    8-13 Just Finish it up uva11093
    8-11 Add All uva 10954
    8-2 Building for UN Uva1605
    css定位.py
    处理HTML5视频播放.py
  • 原文地址:https://www.cnblogs.com/soulDn/p/5913416.html
Copyright © 2020-2023  润新知