欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

iOS App中UILabel的自定義及在Auto Layout中的使用

 更新時間:2016年03月13日 09:25:33   作者:ForeverYoung21  
這篇文章主要介紹了iOS App中UILabel的自定義及在Auto Layout中的使用,示例代碼為傳統(tǒng)的Objective-C語言,需要的朋友可以參考下

自定義UILabel,接受觸摸事件:

復(fù)制代碼 代碼如下:

#import <UIKit/UIKit.h>
 
@interface myLabel : UILabel
 
@end

復(fù)制代碼 代碼如下:

#import "myLabel.h"

@implementation myLabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"myLabel touch");
}

@end


復(fù)制代碼 代碼如下:

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor greenColor]];
   
    myLabel *label = [[myLabel alloc] init];
    label.frame = CGRectMake(60, 100, 200, 50);
    label.text = @"Hello world";
    label.backgroundColor = [UIColor blueColor];
   
    label.userInteractionEnabled = YES;
   
    [self.view addSubview:label];
}
 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
   NSLog(@"viewController touch");
}


如果label.userInteractionEnabled = NO; (默認值),當(dāng)用戶點擊label時將顯示“viewController touch”。

如果在myLabe中加入:

復(fù)制代碼 代碼如下:

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
     NSLog(@"myLabel touch");
     [self.nextResponder touchesBegan:touches withEvent:event];  // 接受到事件后繼續(xù)向上傳遞事件
 }

UILabel在Autolayout中的使用

UILabel在Autolayout中是有些特別的,因為這種可以顯示文本的控件會根據(jù)自身文字的大小,長度等來確定自己的大小。在使用Autolayout時,UILabel這種控件即使不設(shè)置寬度和高度,只設(shè)置x和y,也是沒有問題的。
比如我們先在有一個label,我只設(shè)置了它的x是距離左面16p,y是距離Top Layout Guide 8p,沒有設(shè)置width和height,那么顯示出來是這樣:

201631392420978.png (740×132)

可以看到,如果不設(shè)置寬度和高度,UILabel會根據(jù)文字長度和高度來確定大小。
但是當(dāng)文字長度變長時:

201631392459292.png (744×138)

雖然寬度也在改變,但是也帶來了一個問題:因為文本太長,使label的寬度超出屏幕,多余的部分則不能顯示出來。
我們可以給label增加width的約束,讓它距離右邊界也有16p的距離,然后看看效果:

201631392520721.png (750×112)

可以看到寬度固定了,但是多余的部分又變成了...。
這是因為默認情況下,UILabel只顯示一行,而現(xiàn)在我們寬度又確定,所以多余部分用...來表示。我們只需要將UILabel的numberOfLines改為0,label就會根據(jù)文本的不同行數(shù),顯示對應(yīng)的行數(shù),并且寬度固定。

201631392545872.png (742×474)

但是如果此時減少文字,會發(fā)現(xiàn)label的寬度也是固定的:

有的時候我們201631392605016.png (738×108)不希望它是固定的寬度,而是讓label的寬度和文字的長度一樣,但是最長到距離右邊界16p的地方。
解決方法:

201631392622292.png (504×182)

將原來的Equal改為Greater Than Or Equal,注意此時兩個item的順序,不同的順序關(guān)系也不同?,F(xiàn)在當(dāng)文本多的時候label就會自動變高,當(dāng)文本少的時候label就會自動減小。

相關(guān)文章

最新評論