How do I drag and drop a label to autocomplete textfield? - ios

I want to drag and drop a label or something that will autocomplete the UITextfield. For example if I have an empty textfield and I drag a label with text "hello world" on top of the textfield, the textfield will have "hello world" as its text. Does anyone know how I can do this? Is a UILabel the best choice to use? or perhaps a UIButton could work?

You better read the tutorial first about IOS development. follow the tutorial
in this site http://www.appcoda.com/ios-programming-course/
For your question study the following link first then arise the questions
http://www.appcoda.com/hello-world-build-your-first-iphone-app/
http://www.appcoda.com/ios-programming-basic-how-does-the-hello-world-app-work/

Try this
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//get position
// get label on that position
[label removeFromSuperView];
newLabel = [[UILabel alloc] init];
[self.view addSubView:newLabel]; //positioned at label
}
touchesMoved {
//getPosition
newLabel.position = position;
}
touchesEnded {
//getPosition.
self.view.subviews; // loop and find which view has the position.
UILabel *finalLabel = [[UILabel alloc] init];
finalLabel.center = newLabel.center;
[newLabel removeFromSuperView];
[viewToBeDroppedOn addSubview:finalLabel];
}
Also Check this tutorial Drag & Drop

Related

What is the best way to add UITapGestureRecognizer to a specific part of UILabel?

This question might have asked few times, but I'm still struggling to find best solution. addAttributes with NSMutableAttributedString won't work as I only can give a link to a part of the string.
I have a label with string "Already sign up? Login here". I can get NSRange of text "Login" but how can I give UITapGesture to it? I don't want to use 3rd party library here. Please suggest me some ideas. Thanks
You cannot add a gesture recognizer to a "part of a UILabel". For your case, I would just use two different UILabels: one that is not-tappable that says "Already signed up?", and one that is tappable that says "Sign in here". Honestly, I'd put the tappable part into a UIButton to make it clear. One more option would be to put an empty UIView as a subview of the UILabel, making it the size of the text you want to tap. Then add a gesture recognizer to THAT subview.
(In my opinion, one of the biggest traps developers get into when working with iOS is trying to force it to act differently than designed; like mimicking a web link or something. It always works best, and with a minimum of code, when written to take advantage of its design patterns)
All of the tap location nonsense can be ignored, because that is the point of a recognizer. The recognizer handles all of that for you, and will call your target with the action you set when the UIView is tapped.
So it would basically be:
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:someObject action:#selector(someMethod:)];
[loginLabel addGestureRecognizer:tapRecognizer];
And that's it. The rest will be handled for you by the system. Your target object will be called when the label is tapped. At least, it seems simple from the problem as described in the original post. If there are other complications, please include those points in your question.
Gesture recognizers can't be added to specific parts of a UI component.
However, inside tap handler action, you might want to check
CGPoint tapLocation = [tapRecognizer locationInView:tapRecognizer.view];
You can check if the point lies in your targetRect
if(CGRectContainsPoint(myTargetRect, tapLocation))
{
// Do your action here
}
Hope it helps.
Update:
Here's the Objective-C version for getRect() from #Code 's answer as you needed.
-(CGRect)getRectForString:(NSAttributedString*)str withRange:(NSRange)textRange usingMaxWidth:(CGFloat)maxWidth
{
// Create a layoutManager
NSLayoutManager* layoutManager = [[NSLayoutManager alloc] init];
// Create a textContainer with maxWidth size and add it to layoutManager
NSTextContainer* textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX)];
[layoutManager addTextContainer:textContainer];
textContainer.lineFragmentPadding = 0;
// Create a textStorage with 'str' variable and add the layoutManager to this textStorage
NSTextStorage* textStorage = [[NSTextStorage alloc] initWithAttributedString:str];
[textStorage addLayoutManager:layoutManager];
// Query the actualGlyphRange from layoutManager for specified textRange
NSRange actualGlyphRange;
[layoutManager characterRangeForGlyphRange:textRange actualGlyphRange:&actualGlyphRange];
// Find out the boundingRect for actualGlyphRange
return [layoutManager boundingRectForGlyphRange:actualGlyphRange inTextContainer:textContainer];
}
You can't add tap gesture to a specific part of UILabel or if you tried to do so, you will stuck in finding frames and part of label that might help you at this point but it will be more problematic if it is inside some other view like UITableViewCell etc. It may require some calculation for point conversion with respect to parent/child view.
To keep it simple, my suggestion would be to create a UIView with a UILabel and UIButton embedded in it and button is set next to UILabel.
An example:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Create label
UILabel *lbl = [[UILabel alloc] init];
[lbl setText:#"Already Sign up ? "];
[lbl sizeToFit];
// Create button
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:#"Login Here" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(didTapLink:) forControlEvents:UIControlEventTouchUpInside];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn sizeToFit];
[btn setFrame:CGRectMake(lbl.frame.size.width, lbl.frame.origin.y, btn.frame.size.width, lbl.frame.size.height)];
// Create container that embeds the label and button
UIView *customLabel = [[UIView alloc] initWithFrame:CGRectMake(0, 50, lbl.frame.size.width + btn.frame.size.width, lbl.frame.size.height)];
[customLabel addSubview:lbl];
[customLabel addSubview:btn];
// Add this custom label to UI
[self.view addSubview:customLabel];
}
-(void)didTapLink:(id)sender
{
NSLog(#"Button tapped");
}
Screenshot:
Hope that helps!

UITextField is cutting off the right side of text and not displaying the cursor at the correct position

This problem can be demonstrated by creating a new project in Xcode (I am using version 6.4) and using the following code:
#interface ViewController ()
#property (nonatomic, strong) UITextField * myTextField;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(50, 50, self.view.frame.size.width-100, 50)];
self.myTextField.textAlignment = NSTextAlignmentRight;
[self.myTextField becomeFirstResponder];
self.myTextField.backgroundColor = [UIColor lightGrayColor]
self.myTextField.adjustsFontSizeToFitWidth = YES;
self.myTextField.font = [UIFont systemFontOfSize:40];
[self.view addSubview:self.myTextField];
}
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.myTextField.text = #"1.5241578750119E18";
}
When running this project in iOS Simulator (iPhone 5 or 5S), the cursor is initially displayed after the last "1", and the "8" is not visible until a new character is typed.
This appears to be a bug by Apple, but my question is: is there a workaround for now that will force the text to right-align and show the cursor in the correct position?
To clarify the question further, the issue occurs when the text is set programmatically. I expect to see this:
But instead I am seeing this (note that the entire number is not visible and the cursor is showing after the "1" instead of the last digit which is an "8"):
This is a bug, existing in iOS, since iOS 7. Issue can be reproduced in stock applications like Settings as well. It affects text fields only when NSTextAlignmentRight is used. The original bug ID logged into Radar for this issue is 14485694. You may use centre or left text alignments, to circumvent this problem.
I would also suggest to file a new bug report to Apple,
Try this
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
self.myTextField.leftView = paddingView;
self.myTextField.leftViewMode = UITextFieldViewModeAlways;
it will add some space to the left side of your TextField so that your cursor starts at correct position.
Hope it helps.
If I change your code to this:
- (void)viewDidLoad {
[super viewDidLoad];
self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(5, 50, self.view.frame.size.width-10, 50)];
self.myTextField.textAlignment = NSTextAlignmentRight;
[self.myTextField becomeFirstResponder];
self.myTextField.backgroundColor = [UIColor lightGrayColor];
self.myTextField.adjustsFontSizeToFitWidth = YES;
self.myTextField.font = [UIFont systemFontOfSize:60];
[self.view addSubview:self.myTextField];
}
And start typing in those numbers, the cursor ends up along the right edge of the text field just as it's supposed to.
Even when I start the app with the default value in the text, I see the cursor along the right edge of the text field fine.
Listening to UITextFieldTextDidChangeNotification notification instead of UIControlEventEditingChanged will fix the issue.
I met the same issue, try add dummy code like this
(void)textFieldDidBeginEditing:(UITextField *)textField {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
textField.text = textField.text;
});
}

Swift : How to open a link when tap on text in label?

I want to add a link to some text. At the moment the text is in a UILabel. I want the link to be on the text so the user would not visually see the link. How can this be done?
In web development it looks like this.
Example 1
UILabel is not made for that, but you can link the text with an action (like tapping) in order to do whatever you like. Don't know about swift but in Objective-C is something like:
// If you have UILabel* myLabel
myLabel.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(myAction:)];
[myLabel addGestureRecognizer:gr];
gr.numberOfTapsRequired = 1;
gr.cancelsTouchesInView = NO;
And then you can add the action:
- (void) myAction: (UITapGestureRecognizer *) gr {
// Code here
}
Maybe you can figure out how to do this in swift
You can also make a button look invisible. This could create the effect you are looking for.

Make only part of a sentence a link (add selector)

so I am trying to implement the following. I have a view, which has a sentence. Only part of the sentence links to another view. This is what it looks like:
I am a cat. Learn More
The Learn More would be a link (blue in color), which when clicked would open another view.
Currently I am using a UILabel to write "I am a cat". I realize that the best way to add selectors is to use a button, so "Learn More" should be a button?
Is there any way to write this sentence out without using two different UIComponents?
If not, then how do I make the UILabel and the UIButton completely horizontally aligned with each other?
The following is my code for the label in -layoutSubviews:
CGSize labelSize = [_label.text sizeWithFont:_label.font constrainedToSize:bounds.size lineBreakMode:_label.lineBreakMode];
_label.frame = CGRectMake(0, 0, bounds.size.width - kMarginForText, labelSize.height);
_label.center = CGPointMake(horizontalCenter, CGRectGetMaxY(_previousLabel.frame) + kDistanceBetweenPreviousAndCurrentLabel);
And the code for the label itself.
_label = [[UILabel alloc] initWithFrame:CGRectZero];
_label.text = "I am a cat";
_label.font = [UIFont systemFontOfSize:14];
_label.textAlignment = NSTextAlignmentCenter;
_label.numberOfLines = 0;
_label.lineBreakMode = UILineBreakModeWordWrap;
[self addSubview:_label];
Any help would be appreciated!
To answer your question about a single UIComponent, you could use a UILabel in conjunction with a UITapGestureRecognizer to create the intended effect. Granted this would make the whole label tappable... but having a bigger tap target area is almost never a bad thing.
In particular you would use an NSAttributedString to set the label text (NSAttributedString change color at end of string):
UILabel *label = [[UILabel alloc] init];
//Use initwithframe or setup your constraints after initialization here
label.attributedText = (your nsattributed string here)
Then to initialize the tap recognizer onto the UILabel you would do something like this:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(userDidTapLearnMore)];
label.userInteractionEnabled = YES;
[label addGestureRecognizer:tap];
What you want to do is to align them by their baselines, which you can easily do in Interface Builder by selecting them and choosing Editor > Align > Baselines, as shown in this illustration:

How to right align text of UISearchbar in iOS7

Could you tell me how to right align UISearchbar text in iOS 7? , I was using this in iOS6 but now it does not work in iOS7:
//hacking search bar
UITextField *searchField;
for (UIView *subview in self.searchBar.subviews)
{
if ([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField *)subview;
break;
}
}
if (searchField) {
searchField.textAlignment = NSTextAlignmentRight;
}
Unfortunately this cannot be done safely without completely re-implementing the class from scratch, as text alignment is adjusted by the internals of the object's code when the user begins and finishes editing.
The closest thing to what you want to do would be to use the three position adjustments to shift the text horizontally, but this doesn't affect alignment, only absolute position, and even then only when the user is typing.
If you want to try this, look up searchTestPositionAdjustment, setPositionAdjustment:forSearchBarIcon:, and searchFieldBackgroundPositionAdjustment. I don't think it will be of much use to you though.
-Ash
It's too late, but if anyone is still wondering the solution, then you can follow this.
UITextField *searchTextField = [searchBarController.searchBar valueForKey:#"_searchField"];
You can get the search field using above code. Now simply use the properties you want to use, like.
searchTextField.layer.cornerRadius = 10.0f;
searchTextField.textAlignment = NSTextAlignmentRight;
I've got a solution to this problem. It's a bit hacky and not very neat, but it does the trick.
Since UISearchBar itself does not allow you to edit the placeholder, I've set a UITextField underneath it and disabled it from any touches by doing this:
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if([touch.view isDescendantOfView:self.placeHolderTextField]){
return NO;
}
return YES;
}
Note: don't forget to include <UIGestureRecognizerDelegate> in your .h file.
If this doesn't work however, you can always use [self.view sendSubViewToBack:self.placeholderTextField];
Next on, I've just set events on which I want to display the placeholder and when not.
In the viewDidLoad, I'm just calling self.placeHolderTextFiew.placeholder = #"search"
And in
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length > 0){
self.placeHolderTextfield.placeholder = #"";
} else{
self.placeHolderTextfield.placeholder = #"search";
}
}
Note again: Make sure to include <UISearchBarDelegate> in your .h file in order for this to work.
I am using a tableView as well, so when the method DidSelectRowAtIndexPath is called, I'm also setting the placeholder to an empty string.
Hope this helps.
you can try like this also..
searchbar.placeholder = #"Hai.. whitespace ";
way to set text right align
searchbar->attribute inspector->search text->custom offset->horizontal(set as per requirement)
After playing with subviews of UISearchBar I found this solution, it works for iOS 6 and iOS 7
//hacking search bar
UITextField *searchField;
for (UIView *subview in self.searchBar.subviews)
{
//this will work in iOS 7
for (id sub in subview.subviews) {
if([NSStringFromClass([sub class]) isEqualToString:#"UISearchBarTextField"])
{
[sub setTextAlignment:NSTextAlignmentRight];
}
}
//this will work for less than iOS 7
if ([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField *)subview;
break;
}
}
//for less than iOS 7
if (searchField) {
searchField.textAlignment = NSTextAlignmentRight;
}

Resources