UITextField和UITextView

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sndongcheng/article/details/82751254


#import "ViewController.h"

@interface ViewController ()<UITextFieldDelegate,UITextViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置屏幕大小
    CGRect screen = [[UIScreen mainScreen] bounds];
    
    
    //设置textField的尺寸
    CGFloat textFieldWidth = 223;
    CGFloat textFieldHeight = 30;
    CGFloat textFieldTopView = 150;
    //实例化textField
    UITextField* textField = [[UITextField alloc] initWithFrame:CGRectMake((screen.size.width-textFieldWidth)/2, textFieldTopView, textFieldWidth, textFieldHeight)];
    //设置textField的样式
    textField.borderStyle = UITextBorderStyleRoundedRect;
    //将当前视图控制器self赋值给textField的delegate委托属性
    textField.delegate = self;
    //将textView添加到当前视图
    [self.view addSubview:textField];
    //设置label标签
    CGFloat labelNameTextFieldSpace = 30;
    UILabel* labelName = [[UILabel alloc] initWithFrame:CGRectMake(textField.frame.origin.x, textField.frame.origin.y-labelNameTextFieldSpace, 51, 21)];
    labelName.text = @"Name:";
    [self.view addSubview:labelName];
    
    
    //设置textView的尺寸
    CGFloat textViewWidth = 236;
    CGFloat textViewHeight = 198;
    CGFloat textViewTopView = 240;
    //实例化textView
    UITextView* textView = [[UITextView alloc] initWithFrame:CGRectMake((screen.size.width-textViewWidth)/2, textViewTopView, textViewWidth, textViewHeight)];
    textView.text = @"我是textView中的文字";
    textView.delegate = self;
    [self.view addSubview:textView];
    //设置label标签
    CGFloat labelNameTextViewSpace = 30;
    UILabel* labelName2 = [[UILabel alloc] initWithFrame:CGRectMake(textView.frame.origin.x, textView.frame.origin.y-labelNameTextViewSpace, 103, 21)];
    labelName2.text = @"Abstract:";
    [self.view addSubview:labelName2];
     
    
}

#pragma mark -- 实现UITextFieldDelegate委托协议方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"TextField获得焦点,点击return键");
    return YES;
}

#pragma mark -- 实现UITextViewDelegate委托协议方法
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        NSLog(@"TextView获得焦点,点击return键");
        return NO;
    }
    return YES;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

猜你喜欢

转载自blog.csdn.net/sndongcheng/article/details/82751254