iOS UI基礎-10.0 QQ聊天布局之鍵盤及文本使用


要實現的效果:

 

這里只說用到的幾個知識點

1.圖片包含文字

在設置文字的Frame的時候,使用背景(按鈕)的尺寸,文字使用了內邊距

背景圖片,使用拉伸

/**
 *  返回一張可以隨意拉伸不變形的圖片
 *
 *  @param name 圖片名字
 */
+ (UIImage *)resizableImage:(NSString *)name
{
    UIImage *normal = [UIImage imageNamed:name];
    CGFloat w = normal.size.width * 0.5;
    CGFloat h = normal.size.height * 0.5;
    return [normal resizableImageWithCapInsets:UIEdgeInsetsMake(h, w, h, w)];
}

使用的時候:

   [self.textView setBackgroundImage:[UIImage resizableImage:@"chat_send_nor"] forState:UIControlStateNormal];

2. 給輸入框增加空格符

    //  設置文本框左邊顯示的view
    self.inputView.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 0)];
    // 永遠顯示
    self.inputView.leftViewMode = UITextFieldViewModeAlways;

3.給輸入框的鍵盤設置發送按鈕

設置為send ,並打上勾,如下圖

實現代理UITextFieldDelegate,部分代碼

@interface MJViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *inputView;
@end

@implementation MJViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 設置文本框代理
    self.inputView.delegate = self;
}

#pragma mark - 文本框代理
/**
 *  點擊了return按鈕(鍵盤最右下角的按鈕)就會調用
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // 1.自己發一條消息
    [self addMessage:textField.text type:MJMessageTypeMe];
    
    // 2.自動回復一條消息
    NSString *reply = [self replayWithText:textField.text];
    [self addMessage:reply type:MJMessageTypeOther];
    
    // 3.清空文字
    self.inputView.text = nil;
    
    // 返回YES即可
    return YES;
}

4.鍵盤顯示和關閉

在viewDidLoad中,監聽鍵盤

    // 2.監聽鍵盤的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

keyboardWillChangeFrame方法

/**
 *  當鍵盤改變了frame(位置和尺寸)的時候調用
 */
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
    // 設置窗口的顏色
    self.view.window.backgroundColor = self.tableView.backgroundColor;
    
    // 0.取出鍵盤動畫的時間
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 1.取得鍵盤最后的frame
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 2.計算控制器的view需要平移的距離
    CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
    
    // 3.執行動畫
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, transformY);
    }];
}

關閉鍵盤

/**
 *  當開始拖拽表格的時候就會調用
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 退出鍵盤
    [self.view endEditing:YES];
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM