Custom TextView control with hovering(Objective-C version)

Hello again.
This time I’m going to explain about a custom textview control with hovering.

The scenario which directed me to build up a control like this as follows.
Let’s say you have a textview(max number of lines 1) with a limited width. When you set a lengthy text on it, it will automatically truncate some part of the text and add 3 dots(…) towards the end.

The solution which I proposed would work like this.
Say you have a textview with a lengthy text, when you tap and hold it, it’ll bring up the entire text(without any truncation) in a hover view/separate view.

Ex:

A textview with a lengthy text.

When you tap and hold the textview…

Now I’m going to the details of the actual implementation.

.h file

#import <UIKit/UIKit.h>

@interface CustomTextView : UITextView

@property(atomic, weak) UIViewController* currentViewController;
@property(atomic, strong) UIView* hoverView;

@end

.m file

#import <Foundation/Foundation.h>
#import "CustomTextView.h"
#import "UIHelper.h"

@implementation CustomTextView

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self)
        [self initialSetup];
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
        [self initialSetup];
    return self;
}

- (void)onLongPress:(UILongPressGestureRecognizer *) longPressGestureRecognizer {
    if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan)
    {
        if(longPressGestureRecognizer.view != nil){
            if ([longPressGestureRecognizer.view isKindOfClass:[UITextView class]]) {
                UITextView *textView = (UITextView*)longPressGestureRecognizer.view;
                
                self.currentViewController = self.window.rootViewController;
                
                NSString *text = textView.text;
                
                CGSize sizeRequired = [textView.text sizeWithAttributes:@{NSFontAttributeName :textView.font}];
                CGFloat widthRequired = sizeRequired.width;
                CGFloat widthAvailable = textView.bounds.size.width;
                if(widthRequired <= widthAvailable) return;
                
                [textView sizeToFit];
                
                CGFloat navigationBarHeight = 0;
                if(self.currentViewController.navigationController.navigationBar != nil) navigationBarHeight = self.currentViewController.navigationController.navigationBar.frame.size.height;
                
                CGFloat toolbarHeight = 0;
                UIToolbar *toolbar = [UIHelper findToolbar:self.currentViewController.view];
                if (toolbar != nil) toolbarHeight = toolbar.frame.size.height;
                
                CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
                CGFloat availableHeight = screenHeight - (navigationBarHeight + toolbarHeight);
                CGPoint currentRelativePoint = [self.currentViewController.view convertPoint:textView.frame.origin toView:nil];
                CGRect originalRect = textView.frame;
                CGFloat currentYPos = (currentRelativePoint.y + originalRect.size.height);
                
                UITextView *innerTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, originalRect.size.width, originalRect.size.height)];
                [innerTextView setFont:[UIFont systemFontOfSize:12]];
                [innerTextView setText:text];
                [innerTextView setFrame:CGRectMake(0, 0, originalRect.size.width, innerTextView.contentSize.height)];
                
                CGRect innerRect = innerTextView.frame;
                if ((availableHeight - currentYPos) >= innerRect.size.height)
                    self.hoverView = [[UIView alloc] initWithFrame:CGRectMake(originalRect.origin.x, (originalRect.origin.y + originalRect.size.height), innerRect.size.width, innerRect.size.height)];
                else
                    self.hoverView = [[UIView alloc] initWithFrame:CGRectMake(originalRect.origin.x, (originalRect.origin.y - innerRect.size.height), innerRect.size.width, innerRect.size.height)];
                
                [self.hoverView.layer setBorderColor:[UIColor purpleColor].CGColor];
                [self.hoverView.layer setBorderWidth:1];
                [self.hoverView.layer setCornerRadius:4];
                
                [self.hoverView addSubview:innerTextView];
                [textView.superview addSubview:self.hoverView];
            }
        }
    }
    else
    {
        if (longPressGestureRecognizer.state == UIGestureRecognizerStateCancelled
            || longPressGestureRecognizer.state == UIGestureRecognizerStateFailed
            || longPressGestureRecognizer.state == UIGestureRecognizerStateEnded)
        {
            if (self.hoverView != nil){
                UITextView *innerTextView = [self.hoverView subviews][0];
                NSMutableArray *words = [NSMutableArray arrayWithArray:[innerTextView.text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
                NSInteger wordCount = [words count];
                double noOfWordsPerSec = 3.33;//average readers are the majority and only reach around 200 wpm.
                double noOfSecsRequired = (ceil)(wordCount/noOfWordsPerSec);
                double bonusSecs = 1.0;
                
                [UIView animateWithDuration:1 delay:(noOfSecsRequired + bonusSecs) options:0
                                 animations:^{
                                     [self.hoverView setAlpha:0.0f];
                                 }
                                 completion:^(BOOL finished){
                                     if (finished)
                                         [self.hoverView removeFromSuperview];
                                 }];
            }
        }
    }
}

- (void)initialSetup {
    self.textContainer.maximumNumberOfLines = 1;
    self.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
    self.scrollEnabled = false;
    self.editable = FALSE;
    self.selectable = FALSE;
    [self setDataDetectorTypes:UIDataDetectorTypeAll];
    
    for (UIGestureRecognizer *recognizer in self.gestureRecognizers) {
        if ([recognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
            recognizer.enabled = NO;
        }
    }
    
    
    UILongPressGestureRecognizer *longPressGesRec = [[UILongPressGestureRecognizer alloc]
                                                     initWithTarget:self
                                                     action:@selector(onLongPress:)];
    [self addGestureRecognizer:longPressGesRec];
}

- (void)awakeFromNib {
    [super awakeFromNib];
}

@end

usage
CustomTextView *ctv = [[CustomTextView alloc] initWithFrame:CGRectMake(65, 300, 150, 30)];
ctv.text = @”replace this with a lengthy text…..”;
[self.view addSubview:ctv];

Please note the followings.

1. The width of the hover view is match with the with of the textview.
2. Depending on the available height, the Hover view will be appeared top or below of the textview.
3. The hover view will be automatically fade away after a certain amount of time – the displaying time will be calculated based on the number of words in the given text.

Thank you and happy coding… 🙂

Custom Hyperlink Control for iOS(Objective-C version)

Here comes the iOS version of the Custom Hyperlink Control. iOS also doesn’t come up with a native Hyperlink Control.

Implementation

#import <UIKit/UIKit.h>

@interface CustomHyperlink : UIControl<UITextViewDelegate>

NS_ASSUME_NONNULL_BEGIN

@property UITextView *innerText;
@property UIColor *defaultColor;
@property UIColor *pressedColor;
@property NSDictionary *hyperlinkAttribute;

@property (assign) SEL action;
@property (readonly, strong, nullable) id target;
@property (readonly, strong, nullable) id param;

- (void)setLinkText:(NSString*) valueIn;
- (NSString*)linkText;
- (void)addTarget:(nullable id)targetIn action:(SEL)actionIn param:(nullable id)paramIn;

NS_ASSUME_NONNULL_END

@end
#import "CustomHyperlink.h"

@implementation CustomHyperlink

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        CGRect parentFrame = self.frame;
        CGRect frame = CGRectMake(0, 0, parentFrame.size.width, parentFrame.size.height);
        [self setHyperlinkColors];
        [self setInnerTextCtrl:frame];
        [self addTarget:self action:@selector(executeOnTappedEvent:) forControlEvents:UIControlEventTouchDown];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setHyperlinkColors];
        [self setInnerTextCtrl:frame];
        [self addTarget:self action:@selector(executeOnTappedEvent:) forControlEvents:UIControlEventTouchDown];
    }
    return self;
}

- (void)addTarget:(nullable id)targetIn action:(SEL)actionIn param:(nullable id)paramIn{
    _target = targetIn;
    _action = actionIn;
    _param = paramIn;
}

- (void)setLinkText:(NSString*)valueIn
{
    [self setHyperlinkAttribute];
    self.innerText.attributedText = [[NSAttributedString alloc] initWithString:valueIn attributes:self.hyperlinkAttribute];
}

- (NSString*)linkText
{
    return self.innerText.text;
}

#pragma tapped event

- (void)executeOnTappedEvent:(UIView *)view
{
    UIColor *beforeColor = self.innerText.textColor;
    [UIView transitionWithView:view
                      duration:1
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        self.innerText.textColor = _pressedColor;
                    }
                    completion:^(BOOL finished){
                        if (finished) {
                            [self.target performSelector:self.action withObject:self.param afterDelay:0.1];
                            self.innerText.textColor = beforeColor;
                        }
                    }];
}

- (void)textViewDidChangeSelection:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
	CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
	CGRect newFrame = textView.frame;
	newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
	textView.frame = newFrame;
	
	CGRect selfFrame = self.frame;
	selfFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
	self.frame = selfFrame;
}

#pragma set methods

- (void)setInnerTextCtrl:(CGRect)frame
{
    self.innerText = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    [self.innerText setFont:[UIFont systemFontOfSize:14]];
    [self.innerText setAutocorrectionType:UITextAutocorrectionTypeNo];
    self.innerText.userInteractionEnabled = FALSE;
    self.innerText.scrollEnabled = FALSE;
    self.innerText.editable = FALSE;
    self.innerText.selectable = FALSE; // Add this property for ios 7 to disable the link type
    [self.innerText setDataDetectorTypes:UIDataDetectorTypeAll];
    self.innerText.delegate = self;
    [self.innerText setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
    [self addSubview:self.innerText];
}

- (void)setHyperlinkColors
{
    self.defaultColor = [UIColor blackColor];
    self.pressedColor = [UIColor greenColor];
}

- (void)setHyperlinkAttribute
{
    self.hyperlinkAttribute = @{NSFontAttributeName:[UIFont systemFontOfSize:self.innerText.font.pointSize], NSForegroundColorAttributeName: _defaultColor, NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)};
}

@end

Typical Usage

CustomHyperlink *hyperlink = [[CustomHyperlink alloc] initWithFrame:CGRectMake(controlXPosition, currentYPosition, controlWidth, controlHeight)];
[hyperlink addTarget:self action:@selector(executeTapEvent:) param:hyperlink];
[self.scrollView addSubview:hyperlink];

Happy coding…. 🙂

Forcing newly entered characters to be in UPPERCASE in a TextBox

For Windows Store Apps(Windows 8.1 & Windows Phone 8.1)


///
<summary>
/// Identify whether the pressed key is a Letter(Ex: a, B..)
/// </summary>

/// <param name="sender"></param>
/// <param name="e"></param>
static void textBox_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
	int keyValue = (int)e.Key;
	if (keyValue >= 0x41 && keyValue <= 0x5A)
		isLetter = true;
}

///
<summary>
/// Identify whether a text PASTE is happened.
/// </summary>

/// <param name="sender"></param>
/// <param name="e"></param>
static void textBox_Paste(object sender, TextControlPasteEventArgs e)
{
	var textBox = sender as TextBox;
	startingLocation = textBox.SelectionStart;
	pasteOccurred = true;
}

///
<summary>
/// Change the newly entered character's case to upper case / a set of characters (Ex: text Paste)
/// </summary>

/// <param name="sender"></param>
/// <param name="e"></param>
static void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
	var textBox = sender as TextBox;
	var newText = textBox.Text;
	int currentPosition = textBox.SelectionStart;

	#region text paste

	if (pasteOccurred)
	{
		string newCharacters = newText.Substring(startingLocation, (currentPosition-startingLocation));
		newText = newText.Remove(startingLocation, newCharacters.Length).Insert(startingLocation, newCharacters.ToUpper());
		textBox.Text = newText;
		textBox.SelectionStart = currentPosition;

		pasteOccurred = false;
		startingLocation = -1;

		return;
	}

	#endregion

	if (!isLetter) return;

	currentPosition = textBox.SelectionStart - 1;
	if (currentPosition < 0) return; 	if (Char.IsLower(newText, currentPosition)) 	{ 		string newCharacter = newText.Substring(currentPosition, 1); 		newText = newText.Remove(currentPosition, 1).Insert(currentPosition, newCharacter.ToUpper()); 		textBox.Text = newText; 		textBox.SelectionStart = currentPosition + 1; 	} 	isLetter = false; } 

For Android(TextWatcher implementation)

 final EditText editText = (EditText) view; //new region force -> uppercase implementation
final TextWatcher textWatcher = new TextWatcher() {
	boolean shouldContinue = true;

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		//To avoid executing of text change listener -> onTextChanged when the time of data binding..
		shouldContinue = editText.hasFocus() ? true : false;
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if(!shouldContinue)return;

		int curCursorLoc = editText.getSelectionEnd();
		if(curCursorLoc < 1) return;

		CharSequence charSet = s.subSequence(start, (start + count));
		if(charSet != null) {
			String upperStr = charSet.toString().toUpperCase();
			StringBuilder stringBuilder = new StringBuilder(s);
			stringBuilder.replace(start, (start + count), upperStr);
			editText.setText(stringBuilder.toString());
			editText.setSelection(curCursorLoc);
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
	}
};

editText.addTextChangedListener(textWatcher);
//endregion

For iOS (iPhone or iPad)


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    BOOL shouldChange;
    NSRange lowercaseCharRange;
	lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];

	if (lowercaseCharRange.location != NSNotFound) {
		textField.text = [textField.text stringByReplacingCharactersInRange:range
																 withString:[string uppercaseString]];
		UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument inDirection:UITextLayoutDirectionRight offset:(range.location + 1)];
		UITextRange *newCursorRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
		[textField setSelectedTextRange:newCursorRange];
		shouldChange = NO;
	}
	else
		shouldChange = YES;

    return shouldChange;
}