Coder Social home page Coder Social logo

uitextview-placeholder's Introduction

UITextView+Placeholder

Build Status CocoaPods

A missing placeholder for UITextView.

Installation

Use CocoaPods.

pod 'UITextView+Placeholder'

Usage

  • Import Dynamic Framework:

    e.g. If you're using CocoaPods with use_frameworks! flag.

    @import UITextView_Placeholder;
  • Import Static Library:

    #import <UITextView+Placeholder/UITextView+Placeholder.h>

Then create UITextView and set placeholder.

  • Implement Objective-C:

    UITextView *textView = [[UITextView alloc] init];
    textView.placeholder = @"How are you?";
    textView.placeholderColor = [UIColor lightGrayColor]; // optional
    textView.attributedPlaceholder = ... // NSAttributedString (optional)
  • Implement Swift:

    let textView = UITextView()
    textView.placeholder = "How are you?"
    textView.placeholderColor = UIColor.lightGray // optional
    textView.attributedPlaceholder = ... // NSAttributedString (optional)

Congratulations! You're done. ๐ŸŽ‰

License

UITextView+Placeholder is under MIT license. See the LICENSE file for more information.

uitextview-placeholder's People

Contributors

bcylin avatar devxoul avatar e-sung avatar fl034 avatar hanl001 avatar natemann avatar onato avatar polonez avatar serkodev avatar ykws avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uitextview-placeholder's Issues

Padding

I'm using this in a custom cell and would like to have the placeholder text have a x padding of 16. Any ways to get this done?

Thanks

import in a Swift file ?

I want to use UITextView-Placeholder, I've installed it with Cocoapods but now I'm wondering how I should import it in order to use it in my Swift file. Thanks!

Crash when use Sougou Input method

2016-01-08 16:43:46.797 MyAPP[14249:60b] UMLOG: error: session_id=D24909DC00345158A3E9FC348CA53AAC, context=Only run on the main thread!
(null)
(
0 CoreFoundation 0x00000001884bef6c + 160
1 libobjc.A.dylib 0x00000001949c81fc objc_exception_throw + 60
2 CoreFoundation 0x00000001884bee10 + 0
3 Foundation 0x0000000188ff6e20 + 88
4 UIFoundation 0x00000001915dc654 + 416
5 UIFoundation 0x00000001915dc318 + 1752
6 UIFoundation 0x000000019160ac2c + 240
7 UIFoundation 0x000000019160e100 + 616
8 UIFoundation 0x000000019160e168 + 36
9 UIFoundation 0x0000000191632a64 + 176
10 UIFoundation 0x000000019163209c + 100
11 UIKit 0x000000018b536a48 + 252
12 UIKit 0x000000018b53692c + 164
13 MyAPP 0x00000001006dfe7c -[UITextView(Placeholder) placeholderLabel] + 168
14 MyAPP 0x00000001006e0228 -[UITextView(Placeholder) placeholder] + 36
15 SogouInputIPhone.dylib 0x0000000102036ea0 APPLE_UIKeyboardImpl_getInputTextField_Placeholder + 136
16 SogouInputIPhone.dylib 0x0000000101e0fb94 _ZN17SogouIMENameSpace13t_quantifiers20CheckShowQuantifiersEiNS_17e_QuantifiersTypeENS_9InputTypeEPti + 22008
17 SogouInputIPhone.dylib 0x0000000101e0fdd0 _ZN17SogouIMENameSpace13t_quantifiers20CheckShowQuantifiersEiNS_17e_QuantifiersTypeENS_9InputTypeEPti + 22580
18 Foundation 0x000000018904040c + 1000
19 libsystem_pthread.dylib 0x0000000195137e1c + 168
20 libsystem_pthread.dylib 0x0000000195137d74 + 0
21 libsystem_pthread.dylib 0x0000000195135554 thread_start + 4
)

2016-01-08 16:43:47.815 MyAPP[14249:f017] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Only run on the main thread!'

๋ฒˆ๋“ค ์•„์ด๋””์— + ๊ฐ€ ๋“ค์–ด๊ฐ€ ์žˆ์–ด์„œ Tuist+SPM์—์„œ ์‚ฌ์šฉํ• ์ˆ˜๊ฐ€ ์—†์–ด์š”...

์•ŒํŒŒ๋‰ด๋ฉ”๋ฆญ์ด๋‚˜ ํ•˜์ดํ”ˆ, ํ”ผ๋ฆฌ์–ด๋“œ๋งŒ ์“ฐ๋ผ๊ณ  ํ•˜๋„ค์š”
ํ˜น์‹œ ์ˆ˜์ • ์˜ˆ์ • ์žˆ์œผ์‹ค๊นŒ์š”?

Invalid bundle identifier 'UITextView+Placeholder'. This string must be a uniform type identifier (UTI) that contains only alphanumeric (A-Z,a-z,0-9), hyphen (-), and period (.) characters.

ใ€optimizeใ€‘Use observer object replace textView itself

Swizzling dealloc and implement kvo method in category is not safe. We can use another observer object and associate it on textView. It can unobserve when textView dealloc.

Some code

@interface UITextView ()
@property (nonatomic, strong) _UITextViewObserver *xx_observer;
@end 

@interface _UITextViewObserver ()
@property (nonatomic, weak) UITextView *textView;
@end

@implementation _UITextViewObserver
+ (NSArray *)observingKeys {
    return @[
        @"attributedText",
        @"bounds",
        @"font",
        @"frame",
        @"text",
        @"textAlignment",
        @"textContainerInset",
        @"textContainer.exclusionPaths"
    ];
}
+ (instancetype)observerWithTextView:(UITextView *)textView
{
    _UITextViewObserver *observer = [_UITextViewObserver new];
    [[NSNotificationCenter defaultCenter] addObserver:observer selector:@selector(update) name:UITextViewTextDidChangeNotification object:textView];
    for (NSString *key in [self.class observingKeys]) {
        [textView addObserver:observer forKeyPath:key options:NSKeyValueObservingOptionNew context:nil];
    }
    observer.textView = textView;
    return observer;
}

- (void)update
{
    [self.textView updatePlaceholderTextView];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    [self update];
}

- (void)dealloc
{
    for (NSString *key in [self.class observingKeys]) {
        [self.textView removeObserver:self forKeyPath:key];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

Get rejected from AppStore

My app was rejected with next message:
2. 5 Performance: Software Requirements
Guideline 2.5.1 - Performance - Software Requirements

Your app uses or references the following non-public APIs:

'ABLE.framework, _placeholderLabel, _file'
The use of non-public APIs is not permitted on the App Store because it can lead to a poor user experience should these APIs change.

Continuing to use or conceal non-public APIs in future submissions of this app may result in the termination of your Apple Developer account, as well as removal of all associated apps from the App Store.

Looks like it`s because of placeholder color. Note that I copied UITextView+Placeholder.h and .m files instead of using pod. What do you think, can I resubmit my app after replacing
color = [textField valueForKeyPath:@"_placeholderLabel.textColor"];
to
color = [UIColor lightGrayColor];
?

Got Reject from AppStore

I got reject from Apple and after I check all my project. I found that we are using Swizzling method to dealloc object. this is another topic I have read and they have the same issues with me. That make me confused for 2 days. Could you please review this.

Link of topic here

UITextField's _placeholderLabel

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Access to UITextField's _placeholderLabel ivar is prohibited. This is an application bug'

iOS 13

Placeholder has wrong font size when UITextView is prepopulated with text

I have a UITextView with font size 22, specified in interface builder. I have the following code in viewDidLoad().

textView.placeHolder = "Placeholder text"
textView.text = "My real text"

The UITextView appears with "My real text" at the correct font size, but when I delete this text to reveal the placeholder, the placeholder font size appears to be 17 (or some smaller default).

delloc error

crash stack:
[UITextView dealloc]
[UITextView dealloc]
...
...
...
[UITextView dealloc]
[UITextView dealloc]
[UITextView dealloc]

ios9.1
only if I put your files in my project, delloc crash, remove files then ok.

TextView resets text if focused again

UiTextView resets the text inside it and places placeholder label even if there is text inside textview written by user. unfocus the textview and then focus again... all text cleared.

Line in swizzledDealloc triggers exception breakpoints

The exception breakpoint is triggered on the line in the try block, and while it does not crash the app it makes using the app in the debugger a pain because it interferes with my ability to identify other exceptions and test my app.

Is there a way to fix this? or even just special case the exception breakpoint behavior?

- (void)swizzledDealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    for (NSString *key in self.class.observingKeys) {
        @try {
            [self removeObserver:self forKeyPath:key];
        }
        @catch (NSException *exception) {
            // Do nothing
        }
    }
    [self swizzledDealloc];
}

It is especially frustrating because it hits that breakpoint for each of the observing keys which typically are the following:

 (lldb) po self.class.observingKeys
<__NSArrayI 0x80a267c0>(
attributedText,
bounds,
font,
frame,
text,
textAlignment,
textContainerInset
)

placeholder do not display

Xcode version: 11.3.1
Mac version: Catalina 10.15.2
code like this:
let addressTextView = UITextView()
addressTextView.placeholderColor = ConstantsHelp.buttonOrTextFieldTextColor
addressTextView.placeholder = "placeholder"
baseView.addSubview(addressTextView)
addressTextView.snp.makeConstraints { (make) in
XXXXXX
}
it works well before but now it dose not display, debug its frame is .zero. so i set layoutIfNeeded(),it can get the right frame . Xcode or swift make a change? o((โŠ™๏นโŠ™))o

@import UIKit;

While compilation in UITextView+Placeholder.h I have a error "Use @import when modules are disabed". Unfortunately I cannot add use_frameworks! to my pod file.
Please replace @import UIKit; with #import <UIKit/UIKit.h> in header file

exclusionPaths problem

When using exclusionPaths of textContainer like
textView.textContainer.exclusionPaths = [UIBezierPath(rect: CGRect(x: 0, y: 0, width: 70, height: 30))] then the placeholder label is not excluded.

One possible solution is replacing placeholderLabel to placeholderTextView and apply exclusionPaths to placeholderTextView as same as its superview(UITextView).

If above solution seems ok, then I will work on.

Interface Builder support [feature-request]

Since Xcode now supports IB_DESIGNABLE to identify an object needs to draw custom and IBInspectable to identify properties that can be populated to the inspector, I tried to add support myself.

IB_DESIGNABLE   // not sure if 100% needed because UITextView might be designable by default
@interface UITextView (Placeholder)
@property (nonatomic, strong) IBInspectable NSString *placeholder;
@property (nonatomic, strong) IBInspectable UIColor *placeholderColor;
@end                          ^^^^^^^^^^^^^

@implementation
#pragma mark - Interface Builder support
- (void)prepareForInterfaceBuilder {
    [super prepareForInterfaceBuilder];
    [self updatePlaceholderLabel];
}
@end

bildschirmfoto 2015-07-02 um 12 04 51

Unfortunately it does not render but since I don't have any time and am on a really tight schedule, I need to open a feature request instead of investigating my self.

Probably one would need to create custom drawing of the placeholder in - [UIViewController prepareForInterfaceBuilder]

Placeholder font changes if the first character entered into the text view is an emoticon

It changes to a monospaced font, like so:

screenshot_29_03_16_15_15

Steps to Reproduce:

  1. Enter emoticon into text view
  2. Delete emoticon

Expected Outcome:
Text view shows placeholder with correct font.

Actual Outcome:
Text view shows placeholder with monospaced font:
<UICTFont: 0x7fc85e9ed660> font-family: "Apple Color Emoji"; font-weight: normal; font-style: normal; font-size: 14.00pt">

Crash when using on TestFlight on iOS 13

Backtrace:

Last Exception Backtrace:
0   CoreFoundation                	0x180afc98c __exceptionPreprocess + 220 (NSException.m:199)
1   libobjc.A.dylib               	0x1808250a4 objc_exception_throw + 56 (objc-exception.mm:565)
2   CoreFoundation                	0x1809f2054 +[NSException raise:format:] + 108 (NSException.m:155)
3   UIKitCore                     	0x184e4efe8 UIKVCAccessProhibited + 284 (UIDebug.m:26)
4   UIKitCore                     	0x184dcd6f4 -[UITextField valueForKey:] + 96 (UITextField.m:3523)
5   Foundation                    	0x180db7778 -[NSObject(NSKeyValueCoding) valueForKeyPath:] + 248 (NSKeyValueCoding.m:511)
6   UITextView_Placeholder        	0x1013f4d64 __50+[UITextView(Placeholder) defaultPlaceholderColor]_block_invoke + 84 (UITextView+Placeholder.m:62)
7   libdispatch.dylib             	0x1807ca184 _dispatch_client_callout + 16 (object.m:495)
8   libdispatch.dylib             	0x18079cf7c _dispatch_once_callout + 28 (once.c:52)
9   UITextView_Placeholder        	0x1013f4d08 +[UITextView(Placeholder) defaultPlaceholderColor] + 56 (once.h:84)
10  UITextView_Placeholder        	0x1013f4f24 -[UITextView(Placeholder) placeholderLabel] + 216 (UITextView+Placeholder.m:92)
11  UITextView_Placeholder        	0x1013f51b4 -[UITextView(Placeholder) setPlaceholder:] + 52 (UITextView+Placeholder.m:121)

iOS13 b5 Crashes when setting an attributed placeholder

When setting an attributed placeholder in iOS13 b5, a crash occurs at dispatch_once in UITextView+Placeholder.m

+ (UIColor *)defaultPlaceholderColor {
    static UIColor *color = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UITextField *textField = [[UITextField alloc] init];
        textField.placeholder = @" ";
        color = [textField valueForKeyPath:@"_placeholderLabel.textColor"];
    });
    return color;
}

For example, in our Swift code,

let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font,
                                                            NSAttributedString.Key.kern: kern,
                                                            NSAttributedString.Key.foregroundColor: Style.placeholderColor]

 textView.attributedPlaceholder = NSAttributedString(string: "Description", attributes: attributes)

Crash on iOS 15

observeValueForKeyPathin the UITextView+Placeholder.m calls [self updatePlaceholderTextView]; which performs bounds change. Then observeValueForKeyPath is called again for the property "bounds" with a change dictionary like this:

{
    kind = 1;
    new = "NSRect: {{..., ...}, {..., ...}}";
}

It creates an infinite loop

Change Usage section of the README.md

My project is in Objective-C.

I got an error "'UITextView+Placeholder/UITextView+Placeholder.h' file not found" after importing this library by 'pod install'.

Then I found that the right way to import "<UITextView_Placeholder/UITextView+Placeholder.h>".
Expect to add another item in the Usage section; like the following:

Import Dynamic Framework:

e.g. If you're using CocoaPods with use_frameworks! flag.

@import UITextView_Placeholder;
Import Static Library:

#import <UITextView+Placeholder/UITextView+Placeholder.h>

Import by pod:
#import <UITextView_Placeholder/UITextView+Placeholder.h>

iOS 13 beta Crashing: "Access to UITextField's _placeholderLabel ivar is prohibited. This is an application bug"

We are using this dependency in our app and as of iOS 13 Beta 2 we are getting crashes because of how the framework uses KVC to access Apple's private APIs.

[textfield setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
"NSGenericException" - reason: "Access to UITextField's _placeholderLabel ivar is prohibited. This is an application bug"

Pretty important fix required here: @devxoul

iOS6 not support

@Property(nonatomic,readonly) NSTextContainer *textContainer NS_AVAILABLE_IOS(7_0);

your code:
x = self.textContainer.lineFragmentPadding + self.textContainerInset.left;
y = self.textContainerInset.top;
width = (CGRectGetWidth(self.bounds) - x - self.textContainer.lineFragmentPadding
- self.textContainerInset.right);

could I set the default value, so I can run in iOS6 ??
// lineFragmentPadding default 5.0
// textContainerInset = (top = 8, left = 0, bottom = 8, right = 0)

willDealloc never execute

I have found an another problem, willDealloc never execute.
So It can't execute [[NSNotificationCenter defaultCenter] removeObserver:self]; in willDealloc's block method ?

When I remove [[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(updatePlaceholderLabel)
name:UITextViewTextDidChangeNotification
object:self];

The below mothod did't exec either..

  • (void)observeValueForKeyPath:(NSString *)keyPath
    ofObject:(id)object
    change:(NSDictionary *)change
    context:(void *)context {
    [self updatePlaceholderLabel];
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.