简单实现评论基本功能 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)
}

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

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

你可能感兴趣的:(简单实现评论基本功能 OC Swift)