简单实现评论基本功能 OC Swift

OC
成员变量贴出来!

    @property (nonatomic, strong) UITableView *myTableView;

    @property (nonatomic, strong) UITextField *myTextField;

    @property (nonatomic, strong) UIButton *myButton;

    @property (nonatomic, strong) NSMutableArray *modelArr;

    @property (nonatomic, strong) NSString *textContent;

初始化控件、一些基本常用的属性、记得添加键盘的通知!

// 初始化控件 
 - (void)creatCustomView{

_myButton = [UIButton buttonWithType:UIButtonTypeCustom];
_myButton.frame = CGRectMake(SCREEN_WIDTH - 40, SCREEN_HEIGHT - 30, 40, 30);
_myButton.backgroundColor = [UIColor greenColor];
[_myButton setTitle:@"发送" forState:UIControlStateNormal];
_myButton.titleLabel.font = [UIFont systemFontOfSize:12];
[_myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_myButton addTarget:self action:@selector(myButtonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_myButton];

_myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 30, SCREEN_WIDTH - 40, 30)];
_myTextField.backgroundColor = [UIColor orangeColor];
_myTextField.textColor = [UIColor blackColor];
_myTextField.delegate = self;
_myTextField.clearButtonMode = UITextFieldViewModeWhileEditing;//右边清除按钮模式
_myTextField.returnKeyType = UIReturnKeySend;//return键格式
_myTextField.placeholder = @"发表你的看法";
_myTextField.clearsOnBeginEditing = YES;//开始编辑时 清空
//    _myTextField.layer.cornerRadius = 15;
//    _myTextField.layer.masksToBounds = YES;// 控制圆角
_myTextField.font = [UIFont systemFontOfSize:12];
_myTextField.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:_myTextField];

//监控键盘状态
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

通过监听键盘状态做相应的处理、获取键盘弹出动画的时间来做自定义动画时间是为了保持控件和键盘动画同步!

// 键盘弹出
- (void)keyboardWillShow:(NSNotification *)notification{

//获取键盘高度
CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
//计算偏移量
CGFloat offY = SCREEN_HEIGHT - 30 - kbHeight;
//获取动画时间
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

[UIView animateWithDuration:duration animations:^{
    // 更改控件frame
    _myTextField.frame = CGRectMake(0, offY, SCREEN_WIDTH - 40, 30);
    _myButton.frame = CGRectMake(SCREEN_WIDTH - 40, offY, 40, 30);
    _myTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, offY);
    // 设置tableview cell滑动最后一行
    [_myTableView setContentOffset:CGPointMake(0, _myTableView.contentSize.height - _myTableView.bounds.size.height) animated:NO];
}];

}

// 键盘收回
- (void)keyboardWillHide:(NSNotification *)notification{

//获取动画时间
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

[UIView animateWithDuration:duration animations:^{
    // 恢复frame
    _myTextField.frame = CGRectMake(0, SCREEN_HEIGHT - 30, SCREEN_WIDTH - 40, 30);
    _myButton.frame = CGRectMake(SCREEN_WIDTH - 40, SCREEN_HEIGHT - 30, 40, 30);
    _myTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 30);
}];
}

点击发送、事件处理!

- (void)myButtonClick{

_textContent = _myTextField.text;

if (![_textContent isEqual: @""]) {
    
    [_modelArr addObject:_textContent];
    [_myTableView reloadData];
    _myTextField.text = @"";//完成textfield 清空
}else {
    
    [SVProgressHUD showInfoWithStatus:@"输入不能为空"];
}

// 设置tableview cell滑动最后一行
[_myTableView setContentOffset:CGPointMake(0, _myTableView.contentSize.height - _myTableView.bounds.size.height) animated:NO];
}

点击键盘的return键、发送跟button处理事件一样、实现textfield的代理方法、记得收回键盘、这里取消textfield的第一响应!

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

[_myTextField resignFirstResponder];

[self myButtonClick];
return YES;
}

数据源!

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
// 自动换行
cell.textLabel.numberOfLines = 0;
// 显示类型
cell.textLabel.lineBreakMode = NSLineBreakByCharWrapping;
if (_modelArr.count != 0) {
    
    cell.textLabel.text = [_modelArr objectAtIndex:indexPath.row];
}
return cell;
}

动态计算文本高度!

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

NSString * textArray = [_modelArr objectAtIndex:indexPath.row];
// 计算文本尺寸
CGSize textSize1 = [textArray boundingRectWithSize:tableView.bounds.size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0]} context:nil].size;

return textSize1.height + 35;
}

添加个手势、只添加点击测试!

//添加手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideTextField)];
[self.view addGestureRecognizer:tap];

// 触摸其他区域 收回键盘
- (void)hideTextField{

[_myTextField resignFirstResponder];
}

最后记得清除通知!

- (void)dealloc{

[[NSNotificationCenter defaultCenter] removeObserver:self];
}

Swift一样实现、只是写法不同!

var myTableView: UITableView!

var myTextField: UITextField!

var myView: UIView!

var myButton: UIButton!

var modelArr = [String]()

var contentText = ""

初始化控件、这个我把控件放在一个自定义View上、省几行代码!

    func creatCustomView() {
    
    myView = UIView.init(frame: CGRect.init(x: 0, y: SCREEN_HEIGHT - 49, width: SCREEN_WIDTH, height: 49))
    myView.backgroundColor = .orange
    self.view.addSubview(myView)
    
    myButton = UIButton.init(type: .custom)
    myButton.frame = CGRect.init(x: SCREEN_WIDTH - 50, y: 0, width: 50, height: 49)
    myButton.setTitle("发送", for: .normal)
    myButton.backgroundColor = .green
    myButton.addTarget(self, action: #selector(myButtonSend), for: .touchUpInside)
    myView.addSubview(myButton)
    
    myTextField = UITextField.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH - 50, height: 49))
    myTextField.backgroundColor = .red
    myTextField.textColor = .black
    myTextField.delegate = self
    myTextField.clearButtonMode = .whileEditing
    myTextField.returnKeyType = .send
    myTextField.placeholder = "发表你的看法"
    myTextField.clearsOnBeginEditing = true
    myTextField.font = UIFont.systemFont(ofSize: 12)
    myTextField.textAlignment = .left
    myView.addSubview(myTextField)
    
    /// 监控键盘状态
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}

实现通知方法!

/// 键盘呼出
func keyboardWillShow(notification: NSNotification) {
    
    /// 获取键盘偏移量
    let kbHeight = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size.height
    
    /// 计算偏移量
    let offY = SCREEN_HEIGHT - 49 - kbHeight!
    
    /// 获取动画时间(键盘弹出 textfield和键盘动画同步)
    let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval
    
    UIView.animate(withDuration: duration!, animations: {() -> Void in
      
        self.myView.frame = CGRect.init(x: 0, y: offY, width: SCREEN_WIDTH, height: 49)
        self.myTableView.frame = CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: offY)
        self.myTableView.setContentOffset(CGPoint.init(x: 0, y: self.myTableView.contentSize.height - self.myTableView.bounds.size.height), animated: false)
    })
    
}

/// 键盘隐藏
func keyboardWillHide(notification: Notification) {
    
    let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval
    
    UIView.animate(withDuration: duration!, animations: {() -> Void in
        
        self.myView.frame = CGRect.init(x: 0, y: SCREEN_HEIGHT - 49, width: SCREEN_WIDTH, height: 49)
        self.myTableView.frame = CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 49)
    })
    
}

自定义发送按钮!

func myButtonSend() {
    
    contentText = myTextField.text!
    
    print("\(contentText)")
    
    if !contentText.isEmpty {
        
        modelArr.append(contentText)
        myTableView.reloadData()
        myTextField.text = ""
    }else {
        
        print("输入为空")
    }
    
    self.myTableView.setContentOffset(CGPoint.init(x: 0, y: self.myTableView.contentSize.height - self.myTableView.bounds.size.height), animated: false)
}

textfield代理方法、点击发送收回键盘!

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    
    textField.resignFirstResponder()
    myButtonSend()
    
    return true
}

数据源!

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let myCell = tableView.dequeueReusableCell(withIdentifier: "ID")
    
    if modelArr.count != 0 {
        
        myCell?.textLabel?.text = modelArr[indexPath.row]
    }
    /// 自动换行
    myCell?.textLabel?.numberOfLines = 0
    /// 显示类型
    myCell?.textLabel?.lineBreakMode = .byCharWrapping
    
    return myCell!
}

动态计算文本高度!这里有一点说明一下、计算文本的方法提示打不出来、只有自己硬打出来!方法返回的类型是CGRect、可以自己看一下!

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
    let textArray = modelArr[indexPath.row] as String
    
    /// 计算文本尺寸
    let textSize = textArray.boundingRect(with: myTableView.bounds.size, options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine], attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 12)], context: nil)
    
    return textSize.size.height + 35
}

手势!

/// 添加触摸手势
let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapTouch))
self.view.addGestureRecognizer(tap)

/// 触摸其他区域 隐藏键盘
func tapTouch() {
    
    myTextField.resignFirstResponder()
}

移除通知

deinit {
    
    NotificationCenter.default.removeObserver(self)
}

我的更多文章:你等下课滴

您可以关注我以便随时查看我最新的文章,本篇文章是为了做笔记,顺便提供给大家共同学习进步!如果您对本篇文章有任何疑问,请留言给我,有什么错误也可以留言提醒,如果对大家有帮助我很荣幸!感谢!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,050评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,945评论 4 60
  • Swift版本点击这里欢迎加入QQ群交流: 594119878最新更新日期:18-09-17 About A cu...
    ylgwhyh阅读 25,213评论 7 249
  • 今天下午读了《浮生六记》中的“坎坷记愁”一章。 静静的午后,一个人坐在椅子中,哭的像个受了多大委屈的孩子。真的是跟...
    兔娘阅读 649评论 0 4
  • 最近刚刚上完黄老师的P1关于运营人的职业发展和成长路径的课程,作为一个运营小白,刚刚入门,甚至连运营思维都没有养成...
    SofiaTang阅读 1,924评论 0 0