2016年6月8日 星期三

UILabel坑



有時候,可能會希望一堆文字顯示在label上,並且文字對左上,

這時候可以這樣做:




新創一個類別,繼承label,

改寫父類的方法,然後,把你的label的類別指定為這個新label的類別

-(instancetype)initWithFrame:(CGRect)frame
{
    return [super initWithFrame:frame];
}

-(CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
    textRect.origin.y = bounds.origin.y;
    return textRect;
}

-(void)drawTextInRect:(CGRect)rect
{
    CGRect actualRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
    [super drawTextInRect:actualRect];

}


這時候,label別忘了,line要設為0,才會一直換行下去





其他方法還有:

在內容的最後用\n(換行)來調整xd~不過缺點很明顯,如果你的內容過多的話xd~





還有:不要用label,xd~改用textView把user的editable不要打勾,這樣文字一出來就在左上角xd~





當然,我個人認為第一個方法最好用,
另外還有下面最正統的作法:
利用category來做:(為防止小夥伴不知道如何做,下面說細一點):
先選Objective-C File:


然後選取category~選取類別(這邊是label)然後上面file給他取名:



然後在.h.m檔替label擴展一個方法:

- (void) textLeftTopAlign
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12.f], NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    CGSize labelSize = [self.text boundingRectWithSize:CGSizeMake(207, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    CGRect dateFrame =CGRectMake(2, 140, CGRectGetWidth(self.frame)-5, labelSize.height);
    self.frame = dateFrame;
}





之後只要在viewDidLayoutSubviews對你的label呼叫這個方法,來改寫畫面就好了!

-(void)viewDidLayoutSubviews
{
    [self.greenLabel textLeftTopAlign];
    
}




以上放在:
https://github.com/web8246/testUILabel






如果內容的字要動態調整文字大小的話:(下面是說,最大20最小6的字體大小,請幫我自動調整)

  1. m_titleLabel.font = [UIFont systemFontOfSize:20];  
  2.  m_titleLabel.adjustsFontSizeToFitWidth = YES;  
  3.  m_titleLabel.minimumFontSize = 6; 
  4. [ m_titleLabel sizeToFit];


沒有留言:

張貼留言