iOS UITextView,UITextField,UILabel

什么情况下使用标签,文本域和文本视图

UILabel:显示只读文本,最最基本的显示文字的,支持单行或多行,
UITextField:可编辑文本,但是无法换行,只能在一行显示。当点击键盘上的return时会收到一个事件做一件事。当内容太长一行没有完全显示时,提供水平方向的字符的定位seeking。主要用于简短的文字输入
UITextView:可编辑文本,提供换行功能,支持多行时滚动,允许垂直方向的滚动,文字是可选的,可以拷贝,可以选中后调用语言读出来。

UITextView

实现textView里加一个提示的Label,当开始编辑textView时,Label消失,当点击手势触发时,如果textView里文本为空,Label显示。

//
//  ViewController.m
//  UITextView_Base
//
//  Created by  on 2019/7/9.
//  Copyright © 2019 Shae. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITextViewDelegate>
@property (strong,nonatomic)UITextView *myTextView;
@property (strong,nonatomic)UILabel *placeHolderLabel;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTextView=[[UITextView alloc]initWithFrame:CGRectMake(50, 50, 200, 200) textContainer:nil];
    self.myTextView.font=[UIFont systemFontOfSize:12];
    self.myTextView.backgroundColor=[UIColor redColor];
    self.myTextView.delegate=self;
    
    [self.view addSubview:self.myTextView];
    
    self.placeHolderLabel=[[UILabel alloc] initWithFrame:CGRectMake(5, 5, 200, 20)];
    self.placeHolderLabel.text=@"请输入你想要的内容";
    self.placeHolderLabel.font=[UIFont systemFontOfSize:12];
    self.placeHolderLabel.textColor=[UIColor lightGrayColor];
    
    [self.myTextView addSubview:self.placeHolderLabel];
    
    //点击手势
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapedView)];
    [self.view addGestureRecognizer:tap];
}
-(void)tapedView{
    [self.view endEditing:YES];
    if (self.myTextView.text.length==0) {
        self.placeHolderLabel.hidden=NO;
    }
}
//代理方法
- (void)textViewDidChange:(UITextView *)textView{
    if(textView.text.length!=0){
        self.placeHolderLabel.hidden=YES;
    }
}

@end

在这里插入图片描述
在这里插入图片描述

限制字数

#pragma mark textField的字数限制
//在这个地方计算输入的字数
- (void)textViewDidChange:(UITextView *)textView
{
    NSInteger wordCount = textView.text.length;
    if(wordCount>20){
        textView.text=[textView.text substringToIndex:20];
    }
    //[self wordLimit:_remarksCell.rmkTextView];
}

UITextField

基本属性

也可以输入输入法提供的表情。
clearsOnBeginEditing:这个属性,默认为NO,设置为YES,是当你开始编辑的时候,就删除textField里面的所有字符。
[self.view endEditing:YES];切换输入状态,当执行这段代码,弹出的键盘会收回。
autocapitalizationType,设置输入框的首字母是否大写,是个枚举类型。默认是首字母大写,
returnKeyType:return键的类型。
keyboardType:设置textField的弹出键盘类型,也是一个枚举值。
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建一个UITextField对象,并对样式和属性进行设置
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 50, 250, 50)];
    textField.backgroundColor = [UIColor whiteColor];
    textField.placeholder = @"欢迎访问99iOS";;
    textField.textAlignment = NSTextAlignmentCenter;
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.clearsOnBeginEditing = YES;
    textField.keyboardType = UIKeyboardTypeDefault;
    textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    textField.returnKeyType =UIReturnKeyDone;
    textField.clearsOnInsertion = YES;
    [self.view addSubview:textField];
}

在这里插入图片描述

在这里插入图片描述

设置UITextField的边框样式

textField.borderStyle = UITextBorderStyleRoundedRect;//圆角
typedef enum {
UITextBorderStyleNone, // 无边框
UITextBorderStyleLine, // 有黑色边框
UITextBorderStyleBezel, // 有灰色边框和阴影
UITextBorderStyleRoundedRect // 圆角
} UITextBorderStyle;

代理方法

打印range: NSLog(@"%@ ------- %@",NSStringFromRange(range),string);
clear按钮:self.textField.clearButtonMode=UITextFieldViewModeWhileEditing;

//
//  ViewController.m
//  UITextFied_base
//
//  Created by  on 2019/7/10.
//  Copyright © 2019 Shae. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITextFieldDelegate>
@property (strong,nonatomic)UITextField *textField;
@property (strong,nonatomic)UIButton *button;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.textField=[[UITextField alloc]initWithFrame:CGRectMake(100, 100, 100, 30)];
    //直接创建并添加后,textField已经存在了,能编辑,但是看不见,需要设置颜色,或者边框风格
    //_textField.backgroundColor=[UIColor redColor];
    //最常用的风格
    self.textField.borderStyle=UITextBorderStyleRoundedRect;
    //对齐方式
    self.textField.textAlignment=NSTextAlignmentLeft;
    self.textField.clearsOnBeginEditing=YES;
    //self.textField.keyboardType=UIKeyboardTypeNumberPad;
    self.textField.returnKeyType=UIReturnKeySend;
    self.textField.autocapitalizationType=UITextAutocapitalizationTypeNone;
    //如果不设置代理,代理方法不会生效。
    self.textField.delegate=self;
    self.textField.clearButtonMode=UITextFieldViewModeWhileEditing;
    [self.view addSubview:_textField];
    
    self.button=[UIButton buttonWithType:UIButtonTypeCustom];
    self.button.frame=CGRectMake(200, 100, 50, 30);
    self.button.backgroundColor=[UIColor redColor];
    [self.button addTarget:self action:@selector(clicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button];
    
}
-(void)clicked{
    NSLog(@"%@",self.textField.text);
    [self.view endEditing:YES];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{        // return NO to disallow editing.
    NSLog(@"textFieldShouldBeginEditing----1");
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{           // became first responder
    NSLog(@"textFieldDidBeginEditing-------2");
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{          // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
    NSLog(@"textFieldShouldEndEditing------3");
    return YES;
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{            // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
    NSLog(@"textFieldDidEndEditing----------4");
}
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason NS_AVAILABLE_IOS(10_0){// if implemented, called in place of textFieldDidEndEditing:
    NSLog(@"textFieldDidEndEditing----------5");
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{  // return NO to not change text
    NSLog(@"shouldChangeCharactersInRange-------6");
    NSLog(@"%@  -------  %@",NSStringFromRange(range),string);
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{             // called when clear button pressed. return NO to ignore (no notifications)
    NSLog(@"textFieldShouldClear-----7");
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{            // called when 'return' key pressed. return NO to ignore.
    //点击键盘的return按钮时调用,returnKeyType只是改变的样式,调用的代理方法都是这个。
    NSLog(@"textFieldShouldReturn-----8");
     return YES;
    
}

@end

在这里插入图片描述

收起键盘

可取消textefield的选中状态
1:
遵守UITextFieldDelegate协议
self.textField.delegate=self;

//return键收起键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (![textField isExclusiveTouch]) {
        [textField resignFirstResponder];
    }
    return YES;
}

2:按下其他地方收起键盘

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [self.textField resignFirstResponder];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

3.viewWillDisappear

- (void)viewWillDisappear:(BOOL)animated{
    self.accountTextField.text=@"";
    self.passwordTextField.text=@"";
    [self.view endEditing:YES];
}

UILabel

开发中常遇到UI要求文本均匀分布,两端对齐,开始使用在文字中手动打空格的方式,但常常会碰到相同文字有时三个字,有时四个字,五个字,这个时候用打空格的方式就会出现最后面的字或者符号无法对齐。此时,可以采用Category对UILable的文字分布方式进行处理

使用时应注意要在给Lable的frame,text设置完之后再使用,默认使用textAlignmentLeftAndRight即可。若有其他指定宽度要设置,可使用- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth; 若结尾文字以其他固定文字结尾,可替换冒号再使用

在这里插入图片描述

UILabel+TextStyle.h

#if TARGET_OS_MACCATALYST
    #import <AppKit/AppKit.h>
#endif


#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UILabel (TextStyle)
//两端对齐

- (void)textAlignmentLeftAndRight;

//指定Label以最后的冒号对齐的width两端对齐

- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth;

@end

UILabel+TextStyle.m

#import "UILabel+TextStyle.h"

#if TARGET_OS_MACCATALYST
    #import <AppKit/AppKit.h>
#endif


@implementation UILabel (TextStyle)
- (void)textAlignmentLeftAndRight{

[self textAlignmentLeftAndRightWith:CGRectGetWidth(self.frame)];

}

- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth{

if(self.text==nil||self.text.length==0) {

return;

}

CGSize size = [self.text boundingRectWithSize:CGSizeMake(labelWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil].size;

NSInteger length = (self.text.length-1);

NSString* lastStr = [self.text substringWithRange:NSMakeRange(self.text.length-1,1)];

if([lastStr isEqualToString:@":"]||[lastStr isEqualToString:@":"]) {

length = (self.text.length-2);

}

CGFloat margin = (labelWidth - size.width)/length;

NSNumber*number = [NSNumber numberWithFloat:margin];

NSMutableAttributedString* attribute = [[NSMutableAttributedString alloc]initWithString:self.text];
    [attribute addAttribute:NSKernAttributeName value:number range:NSMakeRange(0,length)];

self.attributedText= attribute;

}

@end

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
UITextView是UIKit框架中的一个控件,可以用来显示和编辑长文本。而富文本则是指带有丰富样式的文本,可以设置文字的字体、颜色、大小、间距、行高等属性。 要在UITextView中实现富文本,首先需要创建一个NSAttributedString对象,并通过NSMutableAttributedString来设置文字的样式。NSAttributedString是不可变的,而NSMutableAttributedString可以修改和添加样式。 创建NSMutableAttributedString对象后,可以使用其方法来设置文字的样式,比如设置字体可以使用NSFontAttributeName属性,设置颜色可以使用NSForegroundColorAttributeName属性,设置字号可以使用NSFontAttributeName属性,设置段落样式可以使用NSParagraphStyleAttributeName属性等等。 设置完成后,就可以将NSMutableAttributedString对象赋值给UITextView的attributedText属性,以实现富文本的显示。 例如,我们想将某个UITextView的文字样式设置为红色、字号为20、字体为粗体,可以按如下方式设置: ``` NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"这是富文本"]; [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, attributedString.length)]; [attributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, attributedString.length)]; textView.attributedText = attributedString; ``` 通过上述代码,就可以在UITextView中显示带有红色、字号为20、字体为粗体的文字。 除了以上示例外,UITextView还支持更多的富文本样式设置,根据具体需求,可以设置更多的属性来实现更丰富的文本效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值