ios UITextView的placeHolder的设置

ios UITextView的placeHolder的设置

我在用UITextView的时候,默认是不能设置placeholder的,于是网上找了一些资料,最后找到了一个别人写的自定义类,拿来用用,顺便分享一下。

CPTextViewPlaceholder.m

//
//  CPTextViewPlaceholder.m
//  Cassius Pacheco
//
//  Created by Cassius Pacheco on 30/01/13.
//  Copyright (c) 2013 Cassius Pacheco. All rights reserved.
//

#import "CPTextViewPlaceholder.h"

@interface CPTextViewPlaceholder()

@property (nonatomic) UITextAutocorrectionType originalCorrection;
@property (nonatomic, strong) UIColor *placeholderColor;
@property (nonatomic, strong) UIColor *originalTextColor;
@property (nonatomic, getter = isUsingPlaceholder) BOOL usingPlaceholder;
@property (nonatomic, getter = isSettingPlaceholder) BOOL settingPlaceholder;

@end

@implementation CPTextViewPlaceholder

#pragma mark -
#pragma mark Life Cycle method

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        
        self.placeholderColor = [UIColor lightGrayColor];
        self.originalCorrection = self.autocorrectionType;
        self.originalTextColor = super.textColor;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBeginEditing) name:UITextViewTextDidBeginEditingNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEndEditing) name:UITextViewTextDidEndEditingNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidBeginEditingNotification object:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidEndEditingNotification object:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:self];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    //Fixes iOS 5.x cursor when becomeFirstResponder
    if ([UIDevice currentDevice].systemVersion.floatValue < 6.000000) {
        if (self.isUsingPlaceholder && self.isFirstResponder) {
            self.text = @"";
        }
    }
    
}

#pragma mark -
#pragma mark Notifications

- (void)didBeginEditing
{
    if (self.isUsingPlaceholder) {
        [self sendCursorToBeginning];
    }
}

- (void)didEndEditing
{
    if (self.text.length == 0) {
        [self setupPlaceholder];
    }
}

- (void)textDidChange:(NSNotification *)notification
{
    //self.text received the placeholder text by CPTex tViewPlaceholder
    if (self.isSettingPlaceholder) {
        return;
    }
    
    if (self.text.length == 0) {
        [self setupPlaceholder];
        return;
    }
    
    if (self.isUsingPlaceholder) {
        self.usingPlaceholder = NO;
        NSRange range = [self.text rangeOfString:self.placeholder options:NSLiteralSearch];
        
        if (range.location != NSNotFound) {
            NSString *newText = [self.text stringByReplacingCharactersInRange:range withString:@""];
            super.textColor = self.originalTextColor;
            super.autocorrectionType = self.originalCorrection;
            
            //User pasted a text equals to placeholder or setText was called
            if ([newText isEqualToString:self.placeholder]) {
                [self sendCursorToEnd];
                //this is necessary for iOS 5.x
            } else if (newText.length == 0) {
                [self setupPlaceholder];
                return;
            }
            
            self.text = newText;
        }
    }
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (self.isUsingPlaceholder && action != @selector(paste:)) {
        return NO;
    }
    
    return [super canPerformAction:action withSender:sender];
}

#pragma mark - Getters and Setters

- (void)setAutocorrectionType:(UITextAutocorrectionType)autocorrectionType
{
    [super setAutocorrectionType:autocorrectionType];
    self.originalCorrection = autocorrectionType;
}

- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = placeholder;
    
    if (self.isUsingPlaceholder || self.text.length == 0) {
        [self setupPlaceholder];
    }
}

- (void)setTextColor:(UIColor *)textColor
{
    [super setTextColor:textColor];
    self.originalTextColor = textColor;
}

- (void)setSelectedRange:(NSRange)selectedRange
{
    if (self.isUsingPlaceholder) {
        [self sendCursorToBeginning];
    } else {
        [super setSelectedRange:selectedRange];
    }
}

- (void)setSelectedTextRange:(UITextRange *)selectedTextRange
{
    if (self.isUsingPlaceholder) {
        [self sendCursorToBeginning];
    } else {
        [super setSelectedTextRange:selectedTextRange];
    }
}

#pragma mark -
#pragma mark Utilities methods

- (void)setupPlaceholder
{
    super.autocorrectionType = UITextAutocorrectionTypeNo;
    self.usingPlaceholder = YES;
    self.settingPlaceholder = YES;
    self.text = self.placeholder;
    self.settingPlaceholder = NO;
    super.textColor = self.placeholderColor;
    [self sendCursorToBeginning];
}

- (void)sendCursorToBeginning
{
    [self performSelector:@selector(cursorToBeginning) withObject:nil afterDelay:0.01];
}

- (void)cursorToBeginning
{
    super.selectedRange = NSMakeRange(0, 0);
}

- (void)sendCursorToEnd
{
    [self performSelector:@selector(cursorToEnd) withObject:nil afterDelay:0.01];
}

- (void)cursorToEnd
{
    super.selectedRange = NSMakeRange(self.text.length, 0);
}

@end
CPTextViewPlaceholder.h

//
//  CPTextViewPlaceholder.h
//  Cassius Pacheco
//
//  Created by Cassius Pacheco on 30/01/13.
//  Copyright (c) 2013 Cassius Pacheco. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface CPTextViewPlaceholder : UITextView

@property (nonatomic, strong) NSString *placeholder;

@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以通过以下代码实现 UITextView 长按复制粘贴的功能: ```swift // 设置允许复制和粘贴 textView.isSelectable = true textView.allowsEditingTextAttributes = true textView.textContainerInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0) // 添加长按手势识别器 let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:))) textView.addGestureRecognizer(longPressGesture) // 长按手势识别器的响应函数 @objc func longPress(_ gestureRecognizer: UIGestureRecognizer) { // 获取长按的位置 let point = gestureRecognizer.location(in: textView) // 获取长按位置所在的字符索引 let characterIndex = textView.layoutManager.characterIndex(for: point, in: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil) // 判断长按位置是否在文本范围内 if characterIndex < textView.textStorage.length { // 获取长按位置所在的单词 let range = textView.tokenizer.rangeEnclosingPosition(TextViewPosition(document: textView.textStorage), with: .word, inDirection: UITextDirection(rawValue: 1)) let word = textView.text(in: range!) // 弹出菜单 let menuController = UIMenuController.shared if !menuController.isMenuVisible { let copyMenuItem = UIMenuItem(title: "复制", action: #selector(copyText(_:))) let pasteMenuItem = UIMenuItem(title: "粘贴", action: #selector(pasteText(_:))) menuController.menuItems = [copyMenuItem, pasteMenuItem] menuController.setTargetRect(CGRect(x: point.x, y: point.y, width: 0, height: 0), in: textView) menuController.setMenuVisible(true, animated: true) } } } // 复制文本 @objc func copyText(_ sender: Any) { UIPasteboard.general.string = textView.text(in: textView.selectedTextRange!) } // 粘贴文本 @objc func pasteText(_ sender: Any) { if let pasteString = UIPasteboard.general.string { let selectedRange = textView.selectedRange let mutableAttributedString = NSMutableAttributedString(attributedString: textView.attributedText) mutableAttributedString.replaceCharacters(in: selectedRange, with: NSAttributedString(string: pasteString)) textView.attributedText = mutableAttributedString } } ``` 这里使用了 `UITextView` 的 `UITextInputTokenizer` 对象来获取长按位置所在的单词,并通过 `UIMenuController` 弹出菜单来实现复制和粘贴的功能。同时,需要在 `UITextView` 中设置 `isSelectable` 和 `allowsEditingTextAttributes` 属性为 `true`,并添加长按手势识别器来启用长按功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值