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…. 🙂

Custom Hyperlink Control for Windows(Windows 8.1, Windows Phone 8.1)

Ended up building a user control which behaves similarly in both Windows and Windows Phone environments. With this you’ll get the underline effect, stating of default color as well as the press color.
Designer code


<UserControl x:Class="MyApp.Architecture.Controls.CustomHyperlink" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:MyApp.Architecture.Controls" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Background="YellowGreen">
    <HyperlinkButton x:Name="innerHyperlinkCtrl" FontFamily="Segoe WP Light">
        <HyperlinkButton.Content>
            <TextBlock FontFamily="Segoe UI" x:Name="inlineText">
					<Underline>
						<Run x:Name="ulRHlink"/>
					</Underline>
            </TextBlock>
        </HyperlinkButton.Content>
    </HyperlinkButton>
</UserControl>

C# code


public sealed partial class CustomHyperlink : UserControl
{
	private HyperlinkButton innerCtrl;
	private TextWrapping textWrapping = TextWrapping.WrapWholeWords;

	#region Constructors

	public CustomHyperlink()
	{
		this.InitializeComponent();
		this.Loaded += CustomHyperlink_Loaded;
		this.InnerCtrl = innerHyperlinkCtrl;

		this.DefaultColor = "#000000";
		this.PressedColor = "#40ff00";
	}

	#endregion

	#region Getters, Setters

	public HyperlinkButton InnerCtrl
	{
		get { return this.innerCtrl; }
		private set { this.innerCtrl = value; }
	}

	#endregion

	#region Events

	void CustomHyperlink_Loaded(object sender, RoutedEventArgs e)
	{
		this.InnerCtrl.Style = (this.Style == null) ? GetDefaultStyle() : this.Style;
		this.inlineText.TextWrapping = this.textWrapping;

		this.InnerCtrl.VerticalAlignment = this.VerticalAlignment;
		this.InnerCtrl.HorizontalAlignment = this.HorizontalAlignment;
		this.InnerCtrl.FontSize = this.FontSize;
		this.InnerCtrl.FontWeight = this.FontWeight;
		this.InnerCtrl.Margin = this.Margin;
	}

	#endregion

	#region Dependency Properties

	public static readonly DependencyProperty LinkTextProperty = DependencyProperty.Register("LinkText", typeof(string), typeof(CustomHyperlink), new PropertyMetadata(null, new PropertyChangedCallback(OnContentChanged)));
	public string LinkText
	{
		get { return (string)GetValue(LinkTextProperty); }
		set { SetValue(LinkTextProperty, value); }
	}

	private static void OnContentChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
	{
		CustomHyperlink mhl = sender as CustomHyperlink;
		mhl.ulRHlink.Text = (e.NewValue != null) ? e.NewValue.ToString() : string.Empty;
	}

	public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register("TextWrapping", typeof(TextWrapping), typeof(CustomHyperlink), null);
	public TextWrapping TextWrapping
	{
		get { return (TextWrapping)GetValue(TextWrappingProperty); }
		set 
		{ 
			SetValue(TextWrappingProperty, value);
			this.inlineText.TextWrapping = value;
		}
	}

	public static readonly DependencyProperty DefaultColorProperty = DependencyProperty.Register("DefaultColor", typeof(string), typeof(CustomHyperlink), null);
	public string DefaultColor
	{
		get { return (string)GetValue(DefaultColorProperty); }
		set { SetValue(DefaultColorProperty, value); }
	}

	public static readonly DependencyProperty PressedColorColorProperty = DependencyProperty.Register("PressedColor", typeof(string), typeof(CustomHyperlink), null);
	public string PressedColor
	{
		get { return (string)GetValue(PressedColorColorProperty); }
		set { SetValue(PressedColorColorProperty, value); }
	}

	public static readonly DependencyProperty NavigateUriProperty = DependencyProperty.Register("NavigateUri", typeof(Uri), typeof(CustomHyperlink), null);
	public Uri NavigateUri
	{
		get { return (Uri)GetValue(NavigateUriProperty); }
		set 
		{ 
			SetValue(NavigateUriProperty, value); 
			this.InnerCtrl.NavigateUri = value; 
		}
	}

	#endregion

	#region Default Style

	private Style GetDefaultStyle()
	{
		StringBuilder styleBuilder = new StringBuilder();
		styleBuilder.Append("<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" 
                      xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" x:Key=\"CustomHyperlinkButtonStyle\" TargetType=\"HyperlinkButton\">");           
			styleBuilder.Append("<Setter Property=\"Template\">");
				styleBuilder.Append("<Setter.Value>");
					styleBuilder.Append("<ControlTemplate TargetType=\"HyperlinkButton\">");
						styleBuilder.Append("<Grid>");
						styleBuilder.Append("<VisualStateManager.VisualStateGroups>");
							styleBuilder.Append("<VisualStateGroup x:Name=\"CommonStates\">");
								styleBuilder.Append("<VisualState x:Name=\"Normal\">");
									styleBuilder.Append("<Storyboard x:Name=\"HyperLinkSBNormal\">");
										styleBuilder.Append("<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=\"Foreground\" Storyboard.TargetName=\"ContentPresenter\">");
											styleBuilder.Append("<DiscreteObjectKeyFrame KeyTime=\"0\" Value=\"" + DefaultColor + "\"/>");
										styleBuilder.Append("</ObjectAnimationUsingKeyFrames>");
									styleBuilder.Append("</Storyboard>");
								styleBuilder.Append("</VisualState>");
								styleBuilder.Append("<VisualState x:Name=\"Pressed\">");
									styleBuilder.Append("<Storyboard x:Name=\"HyperLinkSBPressed\">");
										styleBuilder.Append("<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=\"Foreground\" Storyboard.TargetName=\"ContentPresenter\">");
											styleBuilder.Append("<DiscreteObjectKeyFrame KeyTime=\"0\" Value=\"" + PressedColor + "\"/>");
										styleBuilder.Append("</ObjectAnimationUsingKeyFrames>");
									styleBuilder.Append("</Storyboard>");
								styleBuilder.Append("</VisualState>");
								styleBuilder.Append("<VisualState x:Name=\"Disabled\">");
									styleBuilder.Append("<Storyboard x:Name=\"HyperLinkSBDisabled\">");
										styleBuilder.Append("<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=\"Foreground\" Storyboard.TargetName=\"ContentPresenter\">");
											styleBuilder.Append("<DiscreteObjectKeyFrame KeyTime=\"0\" Value=\"{ThemeResource HyperlinkDisabledThemeBrush}\"/>");
										styleBuilder.Append("</ObjectAnimationUsingKeyFrames>");
									styleBuilder.Append("</Storyboard>");
								styleBuilder.Append("</VisualState>");
							styleBuilder.Append("</VisualStateGroup>");
						styleBuilder.Append("</VisualStateManager.VisualStateGroups>");
						styleBuilder.Append("<ContentPresenter x:Name=\"ContentPresenter\" AutomationProperties.AccessibilityView=\"Raw\" ContentTemplate=\"{TemplateBinding ContentTemplate}\" ContentTransitions=\"{TemplateBinding ContentTransitions}\" Content=\"{TemplateBinding Content}\" HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\">");
						styleBuilder.Append("</ContentPresenter>");
						styleBuilder.Append("</Grid>");
					styleBuilder.Append("</ControlTemplate>");
				styleBuilder.Append("</Setter.Value>");
			styleBuilder.Append("</Setter>");
		styleBuilder.Append("</Style>");

		return (Style)XamlReader.Load(styleBuilder.ToString());
	}

	#endregion
}

Typical Usage (XAML)


<custctrl:CustomHyperlink x:Name="GoogleLink" HorizontalAlignment="Stretch" VerticalAlignment="Center" FontSize="14" Margin="0,20,0,0" NavigateUri="www.google.com" LinkText="Link to Google"/>

Typical Usage(C# class)


CustomHyperlink customHyperlink = new CustomHyperlink();
customHyperlink.Name = standardControlName;
customHyperlink.DefaultColor = "#000000";
customHyperlink.PressedColor = "#40ff00";
customHyperlink.HorizontalAlignment = HorizontalAlignment.Left;
customHyperlink.VerticalAlignment = VerticalAlignment.Center;
customHyperlink.LinkText = "Hello There";

Happy coding…. 🙂

Custom Hyperlink Control for Android

I developed a custom control to mimic the Hyperlink behavior as Android doesn’t have a built-in/native Hyperlink Control.

Implementation

public class CustomHyperlink extends TextView {

    private int mDefaultColor = Color.BLACK;
    private int mPressedColor = Color.GREEN;

    //region #Constructors

    public CustomHyperlink(Context context) {
        super(context);

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE)
                    setTextColor(mPressedColor);
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_OUTSIDE
                        || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    setTextColor(mDefaultColor);
                }
                return false;
            }
        });
    }

    public CustomHyperlink(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomAttrValues(context, attrs);

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE)
                    setTextColor(mPressedColor);
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_OUTSIDE
                        || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    setTextColor(mDefaultColor);
                }
                return false;
            }
        });
    }

    public CustomHyperlink(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomAttrValues(context, attrs);

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE)
                    setTextColor(mPressedColor);
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_OUTSIDE
                        || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    setTextColor(mDefaultColor);
                }
                return false;
            }
        });
    }

    //endregion

    //region #Getters, Setters

    public int getDefaultColor() {
        return mDefaultColor;
    }

    public void setDefaultColor(int defaultColor) {
        this.mDefaultColor = defaultColor;
    }

    public int getPressedColor() {
        return mPressedColor;
    }

    public void setPressedColor(int pressedColor) {
        this.mPressedColor = pressedColor;
    }

    //endregion

    //region #Methods

    public void setLinkText(String value) {
        if (MetrixStringHelper.isNullOrEmpty(value)) return;

        SpannableString content = new SpannableString(value);
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        setText(content);

        setTextColor(mDefaultColor);j
    }

    public void setLinkText(String value, int start, int end) throws Exception {
        if (MetrixStringHelper.isNullOrEmpty(value)) return;

        if (end > value.length())
            throw new Exception(AndroidResourceHelper.getMessage("EndValIsGreaterThan"));

        SpannableString content = new SpannableString(value);
        content.setSpan(new UnderlineSpan(), start, end, 0);
        setText(content);

        setTextColor(mDefaultColor);
    }

    public String getLinkText() {
        return this.getText().toString();
    }

    private void setCustomAttrValues(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomHyperlinkAttr);
		if (typedArray != null) {
			//region #setLinkText
			String s = typedArray.getString(R.styleable.CustomHyperlinkAttr_linkText);
			if (!MetrixStringHelper.isNullOrEmpty(s))
				setLinkText(s);
			//endregion
		}
    }

    //endregion
}

I hope you have some basic understanding about the android custom attributes. You can declare your own attributes in a xml file such as attrs.xml and it can be placed inside res\values\ folder.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomHyperlinkAttr">
        <attr name="linkText" format="string"></attr>
    </declare-styleable>
</resources>

Usage (Inside a XML layout)


<com.architecture.utilities.MetrixHyperlink
ndroid:id="@+id/web_url"
attr:linkText="www.abc.com"
android:gravity="center_horizontal"/>

Don’t forget to add the following line into the top most layout.
xmlns:attr=”http://schemas.android.com/apk/res-auto&#8221;

Ex:


<?xml version="1.0" encoding="utf-8"?> <LinearLayout style="@style/LinearBase.Normal.Vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns="http://schemas.android.com/tools"
xmlns:attr="http://schemas.android.com/apk/res-auto">

Usage (Inside a Class)


CustomHyperlink webUrlHyperLink = (CustomHyperlink) findViewById(R.id.web_url);
webUrlHyperLink.setLinkText("www.xyz.com");

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;
}

Run two instances of the same application in Mac OS

Recently I came across a situation where I needed to run two instances of XCode application to compare two different versions of the project that I’m working.

Once a XCode application is opened and if you want to bring up another instance, you can’t do it by simply tapping on the XCode icon in the shortcut bar/via Applications folder.

You have to execute the following simple command using the Terminal.

open -n /Applications/Xcode.app