textView截取字符串-医生工作台1期

textfield截取字符串

ios7 会崩溃

解:

之前的写法是这样的

正确的写法:

先判断markedTextRange是否为nil,   markedTextRange这个属性是啥意思呢

表示文件中当前选中的文本的长度,参考下面一片文章,详细讲解了这个属性的意思:

http://www.codes51.com/article/detail_349579.html

在解决上述问题的时候你需要判断markedTextRange是不是为Nil,如果为Nil的话就说明你现在没有未选中的字符,可以计算文字长度。否则此时计算出来的字符长度可能不正确

如果选中的长度为nil,即没有选中的长度,那么就正常计算字符串长度,如果超长就截取字符串

如果选中的长度不为nil,就是有选中的,那不用截取字符串,让他正常输入,超出了,真正往textFild填充的时候,, 选中的字符串的长度为nil了,这样就会走if判断,切割字符串


还写了下面的方法:

这个方法的作用是判断,是否需要修改text in range ,是否需要修改某一段文字, 如果不实现这个代理方法,在中文输入法下面,文字长度超出后,点击键盘,还是会联想字符串

里面的判断表示,如果没有选中的文本, 文本的总长度如果超出了限制,就不让它修改 return no

如果没有选中的文本,文本长度没有超出限制,可以修改 return yes

如果有选中的文本,让他修改 return yes


完整代码:

//
//  HDFWorkTableAddCheckItemView.h
//  newDoctor
//
//  Created by songximing on 16/8/20.
//  Copyright © 2016年 haodf.com. All rights reserved.
//

#import <UIKit/UIKit.h>

/**
 *  @author songximing, 16-08-20 16:08:31 22:12 -2
 *
 *  请输入检查项目View
 */
@interface HDFBenchAddCheckItemView : UIView
- (void)show;
@property (nonatomic, copy) HDFStringBlock saveStringBlock; //<!确定按钮保存的字符串

/**
 *  @author songximing, 16-08-20 21:08:01
 *
 *  请输入检查项目View 的初始化方法
 *
 *  @param frame       必须给frame(跟屏幕相等)
 *  @param content     带入的文案内容 第一次进入没有传 nil
 *  @param title       标题 "请输入检查项目" 或者 "请输入检验项目" 两个必须填写一个
 *  @param placeHolder 站位文字 必须传
 *
 *  @return self
 */
- (instancetype)initWithFrame:(CGRect)frame content:(NSString *)content title:(NSString *)title placeHolder:(NSString *)placeHolder;
@property (nonatomic, copy) NSString *cancelString; //!<清空
@end
//
//  HDFWorkTableAddCheckItemView.m
//  newDoctor
//
//  Created by songximing on 16/8/20.
//  Copyright © 2016年 haodf.com. All rights reserved.
//

#import "HDFBenchAddCheckItemView.h"
#import "NSString+HDFAdditions.h"

#define kDescriptionMAXLength 50 //最多50字
#define kTextViewStringWidth kScreenWidth - 50 - 30 // 50是白色View的左右间距  30是textView距离白色view的左右间距
#define kBenchBottomViewHeight 45.0f

@interface HDFBenchAddCheckItemView ()<UITextViewDelegate>
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UIView *whiteContainerView;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIControl *bgCoverControl;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *content; //!<带入的文本内容
@property (nonatomic, copy) NSString *placeHolder; //!<textView站位文字
@end

@implementation HDFBenchAddCheckItemView

- (void)dealloc {
    LOG(@"请输入检查项目View释放了...");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

- (instancetype)initWithFrame:(CGRect)frame content:(NSString *)content title:(NSString *)title placeHolder:(NSString *)placeHolder{
    if (self = [super initWithFrame:frame]) {
        self.title = title;
        self.content = content;
        self.placeHolder = placeHolder;
        [self configUI];
    }
    return self;
}

#pragma mark - UI
- (void)configUI {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    // 灰色遮罩
    UIControl *bgCoverControl = [UIControl hdf_viewWithSuperView:self constraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    } tap:^(UIGestureRecognizer *sender) {
//        [self dismiss];
    }];
    bgCoverControl.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    self.bgCoverControl = bgCoverControl;

    // 白色背景
    UIView *whiteContainerView = [UIView hdf_viewWithSuperView:self constraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.centerX.mas_equalTo(0);
        make.width.mas_equalTo(270);
    }];
    whiteContainerView.backgroundColor = kWColor;
    whiteContainerView.alpha = 0;
    whiteContainerView.layer.cornerRadius = 8;
    whiteContainerView.clipsToBounds = YES;
    self.whiteContainerView = whiteContainerView;

    // title
    UILabel *titleLabel = [UILabel hdf_labelWithText:@"请输入检查项目" font:kFontWithSize(17) superView:whiteContainerView constraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(25);
        make.centerX.mas_equalTo(0);
    }];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    if (self.title.length > 0) { // 设置标题
        titleLabel.text = self.title;
    }

    // 文本输入框
    self.textView = [UITextView hdf_textViewWithPlaceholder:@" " delegate:self superView:whiteContainerView constraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleLabel.mas_bottom).offset(15);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(kFontWithSize(19).lineHeight * 4);
    }];
    self.textView.layer.cornerRadius = 3;
    self.textView.clipsToBounds = YES;
    self.textView.layer.borderWidth = 0.5;
    self.textView.layer.borderColor = kColorWith16RGB(0xcccccc).CGColor;
    self.textView.hdf_placeholder = @"请输入检查项目";

    self.textView.backgroundColor = kColorWith16RGB(0xf8f8f8);
    self.textView.font = kFontWithSize(16);
    self.textView.hdf_placeholderFont = kFontWithSize(16);
    self.textView.hdf_placeholderLabel.numberOfLines = 0;
    self.textView.hdf_placeholderColor = [UIColor redColor];
    [self.textView.hdf_placeholderLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.textView).offset(7.5);
        make.left.mas_equalTo(self.textView).offset(5);
        make.width.mas_equalTo(self.textView.mas_width).offset(-5); // 让站位文字换行
    }];

    if (self.content.length > 0) { // 带入的文本内容
        self.textView.text = self.content;
        self.textView.hdf_placeholder = self.placeHolder;
        self.textView.hdf_placeholderLabel.hidden = YES;
    }else { // 无内容,展示站位文字
        self.textView.hdf_placeholder = self.placeHolder;
        self.textView.hdf_placeholderLabel.hidden = NO;
    }

//    // textView高度自适应内容
//    CGSize textSize = CGSizeZero;
//    if (isIOS(7.0)) {
//        textSize = [self.textView sizeThatFits:CGSizeMake(kTextViewStringWidth, MAXFLOAT)];
//    }
//    else{
//        textSize = self.textView.contentSize;
//    }
//    if (kTextViewHeight < textSize.height) {
//        [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.mas_equalTo(textSize.height);
//        }];
//    }else {
//        [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.mas_equalTo(kTextViewHeight);
//        }];
//    }

    [self createBottomView];
}

- (void)createBottomView {
    UIView *bottomBgView = [[UIView alloc]init];
    [self.whiteContainerView addSubview:bottomBgView];
    [bottomBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_bottom).offset(15);
        make.left.right.equalTo(self.whiteContainerView);
        make.height.mas_equalTo(kBenchBottomViewHeight);
    }];

    // 水平分割线
    UIView *horizontalLineView = [[UIView alloc]init];
    [bottomBgView addSubview:horizontalLineView];
    horizontalLineView.backgroundColor = kG5Color;
    [horizontalLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomBgView);
        make.left.right.equalTo(bottomBgView);
        make.height.mas_equalTo(kLineHeight);
    }];

    // 垂直分割线
    UIView *verticalLineView = [[UIView alloc]init];
    [bottomBgView addSubview:verticalLineView];
    verticalLineView.backgroundColor = kG5Color;
    [verticalLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(bottomBgView);
        make.centerX.equalTo(bottomBgView);
        make.width.mas_equalTo(kLineHeight);
    }];

    kWeakObject(self)
    // 取消 按钮
    UIButton *cancelButton = [UIButton hdf_buttonWithTitle:@"取消" superView:bottomBgView constraints:^(MASConstraintMaker *make) {
        make.top.equalTo(horizontalLineView.mas_bottom);
        make.left.bottom.equalTo(bottomBgView);
        make.right.equalTo(verticalLineView.mas_left);
    } touchup:^(UIButton *sender) {
        [weakObject cancelButtonClick];
    }];
    [cancelButton setTitleColor:kNavColer forState:UIControlStateNormal];
    self.cancelButton = cancelButton;

    UIButton *confirmButton = [UIButton hdf_buttonWithTitle:@"确定" superView:bottomBgView constraints:^(MASConstraintMaker *make) {
        make.top.equalTo(horizontalLineView.mas_bottom);
        make.right.bottom.equalTo(bottomBgView);
        make.left.equalTo(verticalLineView.mas_right);
    } touchup:^(UIButton *sender) {
        [weakObject confirmButtonClick];
    }];
    [confirmButton setTitleColor:kNavColer forState:UIControlStateNormal];

    [self.whiteContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bottomBgView);
    }];
}

#pragma mark - 点击事件
- (void)confirmButtonClick {
    // 去掉首尾的空格
    self.textView.text = [self.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

//    if (self.textView.text.length < 1) {
//        [HDFHud showTip:@"请先输入检查项目"];
//        return;
//    }
    [self dismiss];
    if (self.saveStringBlock) {
        self.saveStringBlock(self.textView.text);
    }
}

- (void)cancelButtonClick {
//    self.textView.text = nil; // 点击取消,清空输入的文字
    [self dismiss];
//    if (self.saveStringBlock) {
//        self.saveStringBlock(self.textView.text);
//    }
}

#pragma UITextViewDelegate
-(void)textViewDidChange:(UITextView *)textView {
    if (self.textView.text.length == 0) {
        self.textView.hdf_placeholderLabel.hidden = NO;
    }else {
        self.textView.hdf_placeholderLabel.hidden = YES;
    }
    // 限制50个字数
    if (textView.markedTextRange == nil) {
        if (self.textView.text.length > kDescriptionMAXLength) {
            //        [HDFHud showTip:@"简介最多输入50个字"];
            self.textView.text = [self.textView.text substringToIndex: kDescriptionMAXLength]; // MAXLENGTH为最大字数
        }
    }

//    // textView高度自适应内容
//    CGSize textSize = CGSizeZero;
//    if (isIOS(7.0)) {
//        textSize = [self.textView sizeThatFits:CGSizeMake(kTextViewStringWidth, MAXFLOAT)];
//    }
//    else{
//        textSize = self.textView.contentSize;
//    }
//
//    if (kTextViewHeight < textSize.height) {
//        [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.mas_equalTo(textSize.height);
//        }];
//        [UIView animateWithDuration:0.25 animations:^{
//            [self layoutIfNeeded];
//        }];
//    }else {
//        [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.mas_equalTo(kTextViewHeight);
//        }];
//    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (textView.markedTextRange == nil) {
        if (range.location >= kDescriptionMAXLength) {
            return NO;
        }
    }
    return YES;
}

#pragma mark - 键盘相关
// Handle keyboard show/hide changes
- (void)keyboardWillShow: (NSNotification *)notification {

    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (UIInterfaceOrientationIsLandscape(interfaceOrientation) && NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) {
        CGFloat tmp = keyboardSize.height;
        keyboardSize.height = keyboardSize.width;
        keyboardSize.width = tmp;
    }

    [self.whiteContainerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(-keyboardSize.height * 0.5);
    }];
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
                     animations:^{
                         [self layoutIfNeeded];
                     }
                     completion:nil
     ];
}

- (void)keyboardWillHide: (NSNotification *)notification {
    [self.whiteContainerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
    }];
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
                     animations:^{
                         [self layoutIfNeeded];
                     }
                     completion:nil
     ];
}

- (void)show {
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    //动画
    CGAffineTransform transform = CGAffineTransformMakeScale(1.2, 1.2);
    self.whiteContainerView.transform = transform;

    [UIView animateWithDuration:0.2 animations:^{
        self.bgCoverControl.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        self.whiteContainerView.alpha = 1; // 子控件的透明度跟着变化
        CGAffineTransform transform = CGAffineTransformMakeScale(1, 1);
        self.whiteContainerView.transform = transform;
    }];
}

- (void)dismiss {
    [UIView animateWithDuration:0.2 animations:^{
        self.bgCoverControl.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
        self.whiteContainerView.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)setCancelString:(NSString *)cancelString {
    _cancelString = cancelString;
    [self.cancelButton setTitle:cancelString forState:UIControlStateNormal];
}

//****以下为解决第一次进入页面,textview不可滚动问题
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    NSString * strText = self.textView.text;
    CGFloat h = [strText heightWithFont:[UIFont systemFontOfSize:16] withLineWidth:kTextViewStringWidth];
    self.textView.contentSize = CGSizeMake(0, h+10);

    return [super hitTest:point withEvent:event];
}

@end
时间: 2024-11-10 07:06:43

textView截取字符串-医生工作台1期的相关文章

医生工作台1期

本周工作内容: 医生工作台需求分析,跟产品探讨实现细节 textView自适应高度, textView弹键盘处理, 讯飞录音 用脑图梳理医生工作台需求, 定义部分页面的类名, 梳理跳转逻辑 患者端 加号改版 review代码 医生工作台需求领读, 确认划分的任务,预估工作量 下周计划: 医生工作台一期进开发 个人成长: 培养规律的作息时间 review代码收获很多, 可以统一团队的代码风格, 提高代码质量 如何让textViiew站位文字换行, 这个textView的站位文字是在原来的textV

js常用的4种截取字符串方法

平常经常把这几个api的参数记混了,于是打算记录下来,当不确定的时候在拿出来翻翻: 在做项目的时候,经常会需要截取字符串,所以常用的方法有slice().substr().substring().match()方法等,四个方法的使用如下所示: 1 <script type="text/javascript"> 2 // 截取字符串的方法 3 //注意1.字符串的截取都是从左向右,不会有从右向左截取:2.slice与substring方法,截取返回的字符串包含numStart

面试题之java 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 要求不能出现截半的情况

题目:10. 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串. 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”. 一.需要分析 1.输入为一个字符串和字节数,输出为按字节截取的字符串-------------->按照字节[byte]截取操作字符串,先将String转换成byte类型 .2.汉字不可以截半----------------------------------

JS简单应用之截取字符串函数以及replace,split函数

JS截取字符串:slice(),substring()和substr()1.substr 方法返回一个从指定位置开始的指定长度的子字符串.stringvar.substr(start [, length ])参数stringvar必选项.要提取子字符串的字符串文字或 String 对象.start必选项.所需的子字符串的起始位置.字符串中的第一个字符的索引为 0.length可选项.在返回的子字符串中应包括的字符个数.说明如果 length 为 0 或负数,将返回一个空字符串.如果没有指定该参数

Java机试题目_怎样截取字符串

面试题1  怎样截取字符串 考题题干 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串.但是要保证汉字不被截半个,如"我ABC"4,应该截为"我AB",输入"我ABC汉DEF"6,应该输出"我ABC",而不是"我ABC+汉的半个". 试题分析 本面试题容易产生困惑的是中文字符和英文字符,在这里需要考虑汉字和英文字符的占用字节数问题,中文字符占两个字节,英文字符占一个字节,理解了这

C#截取字符串

public class SubStrHelper { /// <summary> /// 截取字符串长度,中文二字节 /// </summary> /// <param name="str"></param> /// <param name="length">字节长度</param> /// <returns></returns> public static strin

截取字符串空格

----截取字符串左侧空格 ---- ltrim(表达式) select LTRIM(FName),Fname from T_Personselect LEN(   123),LTRIM(   123) ----截取字符串右侧空格---- rtrim(表达式) select LEN(   123),rtrim(123   )

js如何截取字符串右边指定长度的字符

js如何截取字符串右边指定长度的字符:通常情况下都从字符串的左边开始截取字符串,下面介绍一下如何从字符串的右边截取字符串.代码如下: String.prototype.right=function(length_) { var _from=this.length-length_; if(_from<0) _from=0; return this.substring(this.length - length_,this.length); } var str="antzone"; c

文章生成器,Split方法截取字符串。从硬盘读取文件,和向硬盘存储文件参考代码

string x, y; private void button2_Click(object sender, EventArgs e) { textBox2.Clear(); if (button4.Enabled == false) { string[] shuzu = y.Split(new char[]{'.'}); //用split方法截取字符串 string news = ""; // 将截取字符串后的语句打乱顺序 for (int i = 0; i < shuzu.L