PlaceholderTextView

来源:http://www.cnblogs.com/YouXianMing/archive/2016/07/18/5682275.html
-Advertisement-
Play Games

PlaceholderTextView 效果 源碼 https://github.com/YouXianMing/UI-Component-Collection 的 PlaceholderTextView ...


PlaceholderTextView

 

 效果

 

源碼

https://github.com/YouXianMing/UI-Component-Collection 的 PlaceholderTextView

//
//  PlaceholderTextView.h
//  PlaceholderTextView
//
//  Created by YouXianMing on 16/7/18.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import <UIKit/UIKit.h>
@class PlaceholderTextView;

@protocol PlaceholderTextViewDelegate <NSObject>

@optional

/**
 *  Asks the delegate if editing should begin in the specified text view.
 *
 *  @param textView PlaceholderTextView's object.
 *
 *  @return YEStrue if an editing session should be initiated; otherwise, NOfalse to disallow editing.
 */
- (BOOL)placeholderTextViewShouldBeginEditing:(PlaceholderTextView *)textView;

/**
 *  Asks the delegate if editing should stop in the specified text view.
 *
 *  @param textView PlaceholderTextView's object.
 *
 *  @return YEStrue if editing should stop; otherwise, NOfalse if the editing session should continue
 */
- (BOOL)placeholderTextViewShouldEndEditing:(PlaceholderTextView *)textView;

/**
 *  Tells the delegate that editing of the specified text view has begun.
 *
 *  @param textView PlaceholderTextView's object.
 */
- (void)placeholderTextViewDidBeginEditing:(PlaceholderTextView *)textView;

/**
 *  Tells the delegate that editing of the specified text view has ended.
 *
 *  @param textView PlaceholderTextView's object.
 */
- (void)placeholderTextViewDidEndEditing:(PlaceholderTextView *)textView;

/**
 *  Asks the delegate whether the specified text should be replaced in the text view.
 *
 *  @param textView PlaceholderTextView's object.
 *
 *  @return YEStrue if the old text should be replaced by the new text; NOfalse if the replacement operation should be aborted.
 */
- (BOOL)placeholderTextShouldChangeText:(PlaceholderTextView *)textView;

@end

@interface PlaceholderTextView : UIView

/**
 *  PlaceholderTextView's delegate.
 */
@property (nonatomic, weak) id <PlaceholderTextViewDelegate> delegate;

/**
 *  Current string.
 */
@property (nonatomic, strong, readonly) NSString *currentString;

#pragma mark - UITextView related.

/**
 *  The TextView.
 */
@property (nonatomic, strong, readonly) UITextView   *textView;

/**
 *  The textView's containerInset.
 */
@property (nonatomic) UIEdgeInsets  textContainerInset;

#pragma mark - Placeholder related.

/**
 *  Placeholder attributed string.
 */
@property (nonatomic, strong) NSAttributedString *attributedPlaceholder;

/**
 *  PlaceHorderString gap from left.
 */
@property (nonatomic) CGFloat placeHorderLeftEdge;

/**
 *  PlaceHorderString gap from top.
 */
@property (nonatomic) CGFloat placeHorderTopEdge;

#pragma mark - PlaceholderTextView's event.

/**
 * PlaceholderTextView resign first responder.
 */
- (void)placeholderTextViewResignFirstResponder;

/**
 *  PlaceholderTextView become first responder.
 */
- (void)placeholderTextViewbecomeFirstResponder;

@end
//
//  PlaceholderTextView.m
//  PlaceholderTextView
//
//  Created by YouXianMing on 16/7/18.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import "PlaceholderTextView.h"

@interface PlaceholderTextView () <UITextViewDelegate>

@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UITextView  *textView;
@property (nonatomic, strong) NSString    *currentString;

@end

@implementation PlaceholderTextView

#pragma mark - Frame related method.

- (void)layoutSubviews {

    [super layoutSubviews];
    
    self.textView.frame = self.bounds;
    [self resetPlaceHorderFrame];
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        self.textField             = [[UITextField alloc] init];
        self.textField.enabled     = NO;
        self.textField.textColor   = [UIColor clearColor];
        [self addSubview:self.textField];
        
        self.textView                 = [[UITextView alloc] initWithFrame:self.bounds];
        self.textView.delegate        = self;
        self.textView.backgroundColor = [UIColor clearColor];
        self.textView.textColor       = [UIColor grayColor];
        [self addSubview:self.textView];
    }
    
    return self;
}

#pragma mark - FirstResponder related.

- (void)placeholderTextViewResignFirstResponder {

    [self.textView resignFirstResponder];
}

- (void)placeholderTextViewbecomeFirstResponder {

    [self.textView becomeFirstResponder];
}

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    NSString *currentText = [textView.text stringByReplacingCharactersInRange:range withString:text];
    self.textField.text   = currentText;
    self.currentString    = currentText;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(placeholderTextShouldChangeText:)]) {
        
        return [self.delegate placeholderTextShouldChangeText:self];
        
    } else {
    
        return YES;
    }
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {

    if (self.delegate && [self.delegate respondsToSelector:@selector(placeholderTextViewShouldBeginEditing:)]) {
        
        return [self.delegate placeholderTextViewShouldBeginEditing:self];
        
    } else {
    
        return YES;
    }
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {

    if (self.delegate && [self.delegate respondsToSelector:@selector(placeholderTextViewShouldEndEditing:)]) {
        
        return [self.delegate placeholderTextViewShouldEndEditing:self];
        
    } else {
    
        return YES;
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView {

    if (self.delegate && [self.delegate respondsToSelector:@selector(placeholderTextViewDidBeginEditing:)]) {
        
        [self.delegate placeholderTextViewDidBeginEditing:self];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {

    if (self.delegate && [self.delegate respondsToSelector:@selector(placeholderTextViewDidEndEditing:)]) {
        
        [self.delegate placeholderTextViewDidEndEditing:self];
    }
}

#pragma mark - PlaceHorder related

- (void)resetPlaceHorderFrame {

    self.textField.attributedPlaceholder = _attributedPlaceholder;
    [self.textField sizeToFit];
    
    CGRect newFrame      = self.textField.frame;
    newFrame.origin.x    = _placeHorderLeftEdge;
    newFrame.origin.y    = _placeHorderTopEdge;
    self.textField.frame = newFrame;
}

#pragma mark - Setter & Getter

- (void)setTextContainerInset:(UIEdgeInsets)textContainerInset {

    _textContainerInset          = textContainerInset;
    _textView.textContainerInset = textContainerInset;
}

- (void)setPlaceHorderLeftEdge:(CGFloat)placeHorderLeftEdge {

    _placeHorderLeftEdge = placeHorderLeftEdge;
    [self resetPlaceHorderFrame];
}

- (void)setPlaceHorderTopEdge:(CGFloat)placeHorderTopEdge {

    _placeHorderTopEdge = placeHorderTopEdge;
    [self resetPlaceHorderFrame];
}

- (void)setAttributedPlaceholder:(NSAttributedString *)attributedPlaceholder {

    _attributedPlaceholder = attributedPlaceholder;
    [self resetPlaceHorderFrame];
}

@end
//
//  PlaceholderTextView+ConvenientSetup.h
//  PlaceholderTextView
//
//  Created by YouXianMing on 16/7/18.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import "PlaceholderTextView.h"

@interface PlaceholderTextView (ConvenientSetup)

/**
 *  PlaceholderTextView's placeholderString setup.
 *
 *  @param string   The placeholderString.
 *  @param font     Font.
 *  @param color    Color.
 *  @param leftEdge Gap from left.
 *  @param topEdge  Gap from top.
 */
- (void)placeholderString:(NSString *)string font:(UIFont *)font color:(UIColor *)color leftEdge:(CGFloat)leftEdge topEdge:(CGFloat)topEdge;

/**
 *  PlaceholderTextView's textView setup.
 *
 *  @param font           Font.
 *  @param color          Color.
 *  @param containerInset TextContainerInset.
 */
- (void)textViewFont:(UIFont *)font color:(UIColor *)color containerInset:(UIEdgeInsets)containerInset;

/**
 *  Create the InputAccessoryView with the specified heigh.
 *
 *  @param height The view's height.
 *
 *  @return InputAccessoryView.
 */
- (UIView *)createInputAccessoryViewWithViewHeight:(CGFloat)height;

@end
//
//  PlaceholderTextView+ConvenientSetup.m
//  PlaceholderTextView
//
//  Created by YouXianMing on 16/7/18.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import "PlaceholderTextView+ConvenientSetup.h"

@implementation PlaceholderTextView (ConvenientSetup)

- (void)placeholderString:(NSString *)string font:(UIFont *)font color:(UIColor *)color leftEdge:(CGFloat)leftEdge topEdge:(CGFloat)topEdge {
    
    NSParameterAssert(string);
    NSParameterAssert(font);
    NSParameterAssert(color);
    
    NSString                  *placeHorderString = string;
    NSMutableAttributedString *attributeString   = [[NSMutableAttributedString alloc] initWithString:placeHorderString];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, placeHorderString.length)];
    [attributeString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, placeHorderString.length)];
    
    self.placeHorderLeftEdge   = leftEdge;
    self.placeHorderTopEdge    = topEdge;
    self.attributedPlaceholder = attributeString;
}

- (void)textViewFont:(UIFont *)font color:(UIColor *)color containerInset:(UIEdgeInsets)containerInset {

    self.textView.font      = font;
    self.textView.textColor = color;
    self.textContainerInset = containerInset;
}

- (UIView *)createInputAccessoryViewWithViewHeight:(CGFloat)height {

    UIView *inputAccessoryView         = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, height)];
    inputAccessoryView.backgroundColor = [UIColor clearColor];
    self.textView.inputAccessoryView   = inputAccessoryView;
    
    return inputAccessoryView;
}

@end
//
//  ViewController.m
//  PlaceholderTextView
//
//  Created by YouXianMing on 16/7/18.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import "ViewController.h"
#import "PlaceholderTextView.h"
#import "PlaceholderTextView+ConvenientSetup.h"

@interface ViewController () <PlaceholderTextViewDelegate> {
    
    PlaceholderTextView *_textView;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    UIColor *grayColor  = [UIColor grayColor];
    UIColor *textColor  = [[UIColor blackColor] colorWithAlphaComponent:0.95f];
    UIColor *whiteColor = [UIColor whiteColor];
    UIFont  *font_16    = [UIFont systemFontOfSize:16.f];
    
    // Add UITapGestureRecognizer.
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureEvent)];
    [self.view addGestureRecognizer:tapGesture];
    
    // Create PlaceholderTextView.
    _textView                   = [[PlaceholderTextView alloc] initWithFrame:CGRectMake(0, 20, 320, 180)];
    _textView.layer.borderWidth = 0.5f;
    _textView.delegate          = self;
    [self.view addSubview:_textView];
    
    // Set placeholderString.
    [_textView placeholderString:@"請輸入您的評價(少於50字)" font:font_16 color:grayColor leftEdge:19.f topEdge:15.f];
    
    // Set textView.
    [_textView textViewFont:font_16 color:textColor containerInset:UIEdgeInsetsMake(15.f, 15.f, 15.f, 15.f)];
    
    // Create inputAccessoryView.
    UIView *inputAccessoryView         = [_textView createInputAccessoryViewWithViewHeight:40.f];
    inputAccessoryView.backgroundColor = grayColor;
    
    // Setup inputAccessoryView.
    UIButton *button       = [[UIButton alloc] initWithFrame:inputAccessoryView.bounds];
    button.titleLabel.font = [UIFont systemFontOfSize:14.f];
    [button setTitle:@"確定" forState:UIControlStateNormal];
    [button setTitleColor:whiteColor forState:UIControlStateNormal];
    [button setTitleColor:[whiteColor colorWithAlphaComponent:0.5f] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(inputAccessoryViewEvent) forControlEvents:UIControlEventTouchUpInside];
    [inputAccessoryView addSubview:button];
}

#pragma mark - Event related.

- (void)inputAccessoryViewEvent {
    
    [_textView placeholderTextViewResignFirstResponder];
}

- (void)gestureEvent {

    [self.view endEditing:YES];
}

#pragma mark - PlaceholderTextViewDelegate

- (BOOL)placeholderTextShouldChangeText:(PlaceholderTextView *)textView {
    
    NSLog(@"--> %@", textView.currentString);
    BOOL result; textView.currentString.length >= 50 ? (result = NO) : (result = YES);
    return result;
}

- (BOOL)placeholderTextViewShouldBeginEditing:(PlaceholderTextView *)textView {
    
    NSLog(@"placeholderTextViewShouldBeginEditing");
    return YES;
}

- (BOOL)placeholderTextViewShouldEndEditing:(PlaceholderTextView *)textView {
    
    NSLog(@"placeholderTextViewShouldEndEditing");
    return YES;
}

- (void)placeholderTextViewDidBeginEditing:(PlaceholderTextView *)textView {
    
    NSLog(@"placeholderTextViewDidBeginEditing");
}

- (void)placeholderTextViewDidEndEditing:(PlaceholderTextView *)textView {
    
    NSLog(@"placeholderTextViewDidEndEditing");
}

#pragma mark - System method.

- (void)viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];
    [_textView placeholderTextViewbecomeFirstResponder];
}

@end

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.鏈接樣式設置 設置鏈接樣式時需考慮鏈接是否已被訪問過: 2.小尖角 目前只會一種從網上搜索來的方法: 當 width:0; height:0; 時,各邊會呈現徑向三角形態,可設置各邊高、虛實、顏色,形成小尖角。 ...
  • 線上預覽 源碼下載 這是一組使用CSS3製作的超酷滑鼠滑過圖片標題動畫特效。這組特效中共有8種不同的滑鼠滑過效果,它們都是通過CSS3 transform來製作遮罩層的各種動畫特效。 使用方法 在頁面中引入imghover.css文件。 1 <link rel="stylesheet" type=" ...
  • split() 方法用於把一個字元串分割成字元串數組。<script type="text/javascript"> var str="How are you doing today?" document.write(str.split(" ") + "<br />")document.write( ...
  • 表單校驗是頁面開發中非常常見的一類需求,相信每個前端開發人員都有這方面的經驗。網上有很多成熟的表單校驗框架,雖然按照它們預設的設計,用起來沒有多大的問題,但是在實際工作中,表單校驗有可能有比較複雜的個性化的需求,使得我們用這些插件的預設機制並不能完成這些功能,所以要根據自己的需要去改造它們(畢竟自己 ...
  • [1]創建 [2]本質 [3]稀疏 [4]長度 [5]遍歷 [6]類數組 ...
  • 本章內容: 定義 節點類型 節點關係 選擇器 樣式操作方法style 表格操作方法 表單操作方法 元素節點ELEMENT 屬性節點attributes 文本節點TEXT 文檔節點 Document 位置操作方法 定時器 彈出框 location 其它 事件操作 實例 定義 文檔對象模型(Docume ...
  • (幾個重點概念解析) 一、層疊上下文 二、層疊水平 三、層疊順序(以下層疊順序按照由內向外排列,即z軸上的值越來越大,越靠近用戶) 四、z-index 五、我的理解: 頁面中元素的層疊情況是由層疊順序這個規則決定的。在最初的頁面里,所有元素按照預設的情況依次排列。而z-index屬性像是一個外來戶, ...
  • $('div a'):div標簽下所有層次a元素的jquery對象 $('div>a'):div標簽下子元素層次a元素的jquery對象 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...