UILabel自適配text文本的寬度

#import "ViewController.h"ide


@interface ViewController ()atom


@property (nonatomic, strong) UILabel *fontLabel;spa

@property (nonatomic, strong) UITextField *textField;.net


@end 3d


@implementation ViewControllerorm


- (void)viewDidLoad {server

    [super viewDidLoad];get

    

    _textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 320, 40)];it

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTextField) name:UITextFieldTextDidChangeNotification object:nil];io

    _textField.backgroundColor = [UIColor purpleColor];

    _textField.keyboardType = UIKeyboardTypeEmailAddress;

    _textField.returnKeyType = UIReturnKeyDone;

    _textField.delegate = self;

    [self.view addSubview:_textField];

    

    

    _fontLabel = [[UILabel alloc]initWithFrame:CGRectMake(10,140,320,40)];

    _fontLabel.backgroundColor = [UIColor blueColor];

    NSString *fontString = @"明月幾時有,把酒問酒吧";

    CGSize labelSize = CGSizeMake(320,2000);

    CGSize fontStringSize = [fontString boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13]} context:nil].size;

    

    _fontLabel.frame = CGRectMake(10, 260, fontStringSize.width, 40);

    _fontLabel.text = fontString;

//    [_fontLabel sizeToFit];

    _fontLabel.textAlignment = NSTextAlignmentRight;

    [self.view addSubview:_fontLabel];

    

    UIButton *click = [[UIButton alloc]initWithFrame:CGRectMake(50, 100, 140, 40)];

    [click setTitle:@"點擊我吧" forState:UIControlStateNormal];

    click.backgroundColor = [UIColor redColor];

    [click addTarget:self action:@selector(touchMe) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:click];

    

    

}



- (void)touchMe {

    [_fontLabel sizeToFit];

}


- (void)changeTextField {

     _fontLabel.text = self.textField.text;

//    [_fontLabel sizeToFit];

}

相關文章
相關標籤/搜索