簡(jiǎn)單實(shí)現(xiàn)評(píng)論基本功能 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:@"發(fā)送" 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 = @"發(fā)表你的看法";
_myTextField.clearsOnBeginEditing = YES;//開始編輯時(shí) 清空
//    _myTextField.layer.cornerRadius = 15;
//    _myTextField.layer.masksToBounds = YES;// 控制圓角
_myTextField.font = [UIFont systemFontOfSize:12];
_myTextField.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:_myTextField];

//監(jiān)控鍵盤狀態(tài)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

通過監(jiān)聽鍵盤狀態(tài)做相應(yīng)的處理辆床、獲取鍵盤彈出動(dòng)畫的時(shí)間來做自定義動(dòng)畫時(shí)間是為了保持控件和鍵盤動(dòng)畫同步!

// 鍵盤彈出
- (void)keyboardWillShow:(NSNotification *)notification{

//獲取鍵盤高度
CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
//計(jì)算偏移量
CGFloat offY = SCREEN_HEIGHT - 30 - kbHeight;
//獲取動(dòng)畫時(shí)間
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);
    // 設(shè)置tableview cell滑動(dòng)最后一行
    [_myTableView setContentOffset:CGPointMake(0, _myTableView.contentSize.height - _myTableView.bounds.size.height) animated:NO];
}];

}

// 鍵盤收回
- (void)keyboardWillHide:(NSNotification *)notification{

//獲取動(dòng)畫時(shí)間
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

[UIView animateWithDuration:duration animations:^{
    // 恢復(fù)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);
}];
}

點(diǎn)擊發(fā)送桅狠、事件處理讼载!

- (void)myButtonClick{

_textContent = _myTextField.text;

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

// 設(shè)置tableview cell滑動(dòng)最后一行
[_myTableView setContentOffset:CGPointMake(0, _myTableView.contentSize.height - _myTableView.bounds.size.height) animated:NO];
}

點(diǎn)擊鍵盤的return鍵、發(fā)送跟button處理事件一樣中跌、實(shí)現(xiàn)textfield的代理方法咨堤、記得收回鍵盤、這里取消textfield的第一響應(yīng)漩符!

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

[_myTextField resignFirstResponder];

[self myButtonClick];
return YES;
}

數(shù)據(jù)源一喘!

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

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
// 自動(dòng)換行
cell.textLabel.numberOfLines = 0;
// 顯示類型
cell.textLabel.lineBreakMode = NSLineBreakByCharWrapping;
if (_modelArr.count != 0) {
    
    cell.textLabel.text = [_modelArr objectAtIndex:indexPath.row];
}
return cell;
}

動(dòng)態(tài)計(jì)算文本高度!

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

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

return textSize1.height + 35;
}

添加個(gè)手勢(shì)嗜暴、只添加點(diǎn)擊測(cè)試凸克!

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

// 觸摸其他區(qū)域 收回鍵盤
- (void)hideTextField{

[_myTextField resignFirstResponder];
}

最后記得清除通知议蟆!

- (void)dealloc{

[[NSNotificationCenter defaultCenter] removeObserver:self];
}

Swift一樣實(shí)現(xiàn)、只是寫法不同萎战!

var myTableView: UITableView!

var myTextField: UITextField!

var myView: UIView!

var myButton: UIButton!

var modelArr = [String]()

var contentText = ""

初始化控件咐容、這個(gè)我把控件放在一個(gè)自定義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("發(fā)送", 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 = "發(fā)表你的看法"
    myTextField.clearsOnBeginEditing = true
    myTextField.font = UIFont.systemFont(ofSize: 12)
    myTextField.textAlignment = .left
    myView.addSubview(myTextField)
    
    /// 監(jiān)控鍵盤狀態(tài)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}

實(shí)現(xiàn)通知方法疟丙!

/// 鍵盤呼出
func keyboardWillShow(notification: NSNotification) {
    
    /// 獲取鍵盤偏移量
    let kbHeight = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size.height
    
    /// 計(jì)算偏移量
    let offY = SCREEN_HEIGHT - 49 - kbHeight!
    
    /// 獲取動(dòng)畫時(shí)間(鍵盤彈出 textfield和鍵盤動(dòng)畫同步)
    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)
    })
    
}

自定義發(fā)送按鈕!

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代理方法鸟雏、點(diǎn)擊發(fā)送收回鍵盤享郊!

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

數(shù)據(jù)源!

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

動(dòng)態(tài)計(jì)算文本高度孝鹊!這里有一點(diǎn)說明一下炊琉、計(jì)算文本的方法提示打不出來、只有自己硬打出來又活!方法返回的類型是CGRect苔咪、可以自己看一下!

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

手勢(shì)柳骄!

/// 添加觸摸手勢(shì)
let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapTouch))
self.view.addGestureRecognizer(tap)

/// 觸摸其他區(qū)域 隱藏鍵盤
func tapTouch() {
    
    myTextField.resignFirstResponder()
}

移除通知

deinit {
    
    NotificationCenter.default.removeObserver(self)
}

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

您可以關(guān)注我以便隨時(shí)查看我最新的文章团赏,本篇文章是為了做筆記,順便提供給大家共同學(xué)習(xí)進(jìn)步耐薯!如果您對(duì)本篇文章有任何疑問舔清,請(qǐng)留言給我,有什么錯(cuò)誤也可以留言提醒曲初,如果對(duì)大家有幫助我很榮幸体谒!感謝!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末臼婆,一起剝皮案震驚了整個(gè)濱河市抒痒,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌颁褂,老刑警劉巖故响,帶你破解...
    沈念sama閱讀 216,496評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異颁独,居然都是意外死亡彩届,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門奖唯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人糜值,你說我怎么就攤上這事丰捷∨髂” “怎么了?”我有些...
    開封第一講書人閱讀 162,632評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵病往,是天一觀的道長(zhǎng)捣染。 經(jīng)常有香客問我,道長(zhǎng)停巷,這世上最難降的妖魔是什么耍攘? 我笑而不...
    開封第一講書人閱讀 58,180評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮畔勤,結(jié)果婚禮上蕾各,老公的妹妹穿的比我還像新娘。我一直安慰自己庆揪,他們只是感情好式曲,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著缸榛,像睡著了一般吝羞。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上内颗,一...
    開封第一講書人閱讀 51,165評(píng)論 1 299
  • 那天钧排,我揣著相機(jī)與錄音,去河邊找鬼均澳。 笑死恨溜,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的负懦。 我是一名探鬼主播筒捺,決...
    沈念sama閱讀 40,052評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼纸厉!你這毒婦竟也來了系吭?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,910評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤颗品,失蹤者是張志新(化名)和其女友劉穎肯尺,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體躯枢,經(jīng)...
    沈念sama閱讀 45,324評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡则吟,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了锄蹂。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片氓仲。...
    茶點(diǎn)故事閱讀 39,711評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出敬扛,到底是詐尸還是另有隱情晰洒,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評(píng)論 5 343
  • 正文 年R本政府宣布啥箭,位于F島的核電站谍珊,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏急侥。R本人自食惡果不足惜砌滞,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望坏怪。 院中可真熱鬧贝润,春花似錦、人聲如沸陕悬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽捉超。三九已至胧卤,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間拼岳,已是汗流浹背枝誊。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留惜纸,地道東北人叶撒。 一個(gè)月前我還...
    沈念sama閱讀 47,722評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像耐版,于是被迫代替她去往敵國(guó)和親祠够。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,077評(píng)論 25 707
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫粪牲、插件古瓤、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,094評(píng)論 4 62
  • Swift版本點(diǎn)擊這里歡迎加入QQ群交流: 594119878最新更新日期:18-09-17 About A cu...
    ylgwhyh閱讀 25,365評(píng)論 7 249
  • 今天下午讀了《浮生六記》中的“坎坷記愁”一章亭引。 靜靜的午后绎速,一個(gè)人坐在椅子中,哭的像個(gè)受了多大委屈的孩子焙蚓。真的是跟...
    兔娘閱讀 676評(píng)論 0 4
  • 最近剛剛上完黃老師的P1關(guān)于運(yùn)營(yíng)人的職業(yè)發(fā)展和成長(zhǎng)路徑的課程纹冤,作為一個(gè)運(yùn)營(yíng)小白洒宝,剛剛?cè)腴T,甚至連運(yùn)營(yíng)思維都沒有養(yǎng)成...
    SofiaTang閱讀 1,940評(píng)論 0 0