CGRectMake doesn't work - ios

I'm working on example from "iOS Programming Cookbook", based on iOS 7. I need to create UITextField and add it to ViewController.
In ViewController.m I have:
- (void) viewDidLoad {
[super viewDidLoad];
[self createField];
}
- (void) createField {
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(20.0f, 35.0f, 280.0f, 30.0f)];
self.textField.translatesAutoresizingMaskIntoConstraints = NO;
self.textField.borderStyle = UITextBorderStyleRoundedRect;
self.textField.placeholder = #"Enter text to share";
self.textField.delegate = self;
[self.view addSubview:self.textField];
}
On screenshot from book textField appears in the middle of screen's width under the status bar, but when I run it textField appears on the top left corner of screen behind the status bar.
Maybe the problem is, that I run app on iPhone 6 simulator with iOS 8. But I don't know how to solve it.
Thanks!

Using self.textField.translatesAutoresizingMaskIntoConstraints = NO; is pretty much telling the object that it doesn't really care about the frame but relies more on the constraints that you give it. Setting it to YES takes the frame and automatically applies constraints to it to mimic the frame that you give it.
For example it would apply the constraints to have the frame appear at: CGRectMake(20.0f, 35.0f, 280.0f, 30.0f). When setting it to NO use NSLayoutConstraint and create the constraints programatically.
But in your case just remove the line
self.textField.translatesAutoresizingMaskIntoConstraints = NO;
because it is set to YES by default.

Related

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

iOS - UIView Always on Front without BringSubviewToFront

Can I have some UIView which will always appear on top in iOS?
There are lots of addSubview in my project but I need to have one small view which will always appear. SO is there any other option than
[self.view bringSubViewToFront:myView];
Thanks
One more option (especially if you want to overlap several screens, with logo for example) - separate UIWindow. Use windowLevel to set the level of new window.
UILabel *devLabel = [UILabel new];
devLabel.text = #" DEV ";
devLabel.font = [UIFont systemFontOfSize:10];
devLabel.textColor = [UIColor grayColor];
[devLabel sizeToFit];
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
static UIWindow *notificationWindow;
notificationWindow = [[UIWindow alloc] initWithFrame:
CGRectMake(screenSize.width - devLabel.width, screenSize.height - devLabel.height,
devLabel.width, devLabel.height)];
notificationWindow.backgroundColor = [UIColor clearColor];
notificationWindow.userInteractionEnabled = NO;
notificationWindow.windowLevel = UIWindowLevelStatusBar;
notificationWindow.rootViewController = [UIViewController new];
[notificationWindow.rootViewController.view addSubview:devLabel];
notificationWindow.hidden = NO;
Another option is set layer.zPosition of your UIView.
You need to add
#import <QuartzCore/QuartzCore.h>
Framework to your .m file.
And set such like
myCustomView.layer.zPosition = 101;// set maximum value as per your requirement.
For more information about layer.zPosition read this documentation.
Discussion
The default value of this property is 0. Changing the value of this property changes the the front-to-back ordering of layers onscreen. This can affect the visibility of layers whose frame rectangles overlap.
The other option is to add other subviews below this always-on-top subview. For example:
[self.view insertSubview:subview belowSubview:_topSubview];
There's no solution with Interface Builder if you search for this kind. It should be done programmatically. If you don't want to use bringSubviewToFront: everytime, just insert other subviews below this one.
Many times your view did not appear in viewDidLoad or, if your view comes from parentViewController (for example in many transitions like modal segue..) your can see parentViewController only in viewDidAppear so:
Try to put bringSubviewToFront in :
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.view bringSubViewToFront:myView];
// or if your view is attached in parentViewController
[self.parentViewController.view bringSubViewToFront:myView];
}
Good luck!

Cannot make programmatically created UITextField editable (iOS)

I created a UITextField programatically, (I do not use storyboard) and added it as a subview to ViewController with this code:
#interface ViewController ()
#property (nonatomic, strong) UITextField *searchLocationBar;
#end
...
#synthesize searchLocationBar;
...
self.searchLocationBar = [[UITextField alloc] init];
self.searchLocationBar.frame = CGRectMake(0.0f, 0.0f, 320.0f, 40.0f);
self.searchLocationBar.delegate = self;
self.searchLocationBar.borderStyle = UITextBorderStyleRoundedRect;
self.searchLocationBar.placeholder = #"a temporary placeholder";
self.searchLocationBar.userInteractionEnabled = YES;
self.searchLocationBar.clearButtonMode = UITextFieldViewModeAlways;
[self.view addSubview:self.searchLocationBar];
However, I cannot enter any text - nothing happens, when I tap on a textfield. It's not overlapped by any other view.
I've checked UITextfield not editable-iphone but no effect
I'm newbie and totally sure I simply miss something - please advice.
Thanks!
EDIT:
One more thing: I have a Google Maps GMSMapView assigned to self.view as
self.view = mapView_; as written in Google API documentation.
After some tests I found that with this declaration all controls work perfectly, but not textfields. I would prefer not to move a map view to any subview as I will need to rewrite lots of things.
Can someone please add any suggestions?
you forget add:
[self.view bringSubviewToFront:self.searchLocationBar];
In Xcode 5 your code should work.Better you check your Xcode version.May be the problem with your code with Xcode versions.You can try by following way.
UITextField *lastName = [[[UITextField alloc] initWithFrame:CGRectMake(10, 100, 300, 30)];
[self.view addSubview:lastName];
lastName.placeholder = #"Enter your last name here"; //for place holder
lastName.textAlignment = UITextAlignmentLeft; //for text Alignment
lastName.font = [UIFont fontWithName:#"MarkerFelt-Thin" size:14.0]; // text font
lastName.adjustsFontSizeToFitWidth = YES; //adjust the font size to fit width.
lastName.textColor = [UIColor greenColor]; //text color
lastName.keyboardType = UIKeyboardTypeAlphabet; //keyboard type of ur choice
lastName.returnKeyType = UIReturnKeyDone; //returnKey type for keyboard
lastName.clearButtonMode = UITextFieldViewModeWhileEditing;//for clear button on right side
lastName.delegate = self; //use this when ur using Delegate methods of UITextField
There are lot other attributes available but these are few which we use it frequently.if u wanna know about more attributes and how to use them refer to the following link.
You can also make property for UITextField.Either way should work fine in Xcode.
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextField_Class/Reference/UITextField.html

iOS: Autolayout causing UIScrollView to not scroll

I have set up a UIScrollView with which I want to display 12 images (only 8 fit on screen) laid out horizontally. In the following image you can see the problem I'm having (which makes my scroll view not scroll), my constraints and the UIScrollView which I have added on storyboard:
I have called the following method on -(void)viewDidLoad, where I "set up"my scrollview (itemList is my scroll view property and itemNames a array with the images'names):
- (void)setupHorizontalScrollView
{
self.itemList.delegate = self;
[self.itemList setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.itemList setBackgroundColor:[UIColor blackColor]];
[self.itemList setCanCancelContentTouches:NO];
self.itemList.indicatorStyle = UIScrollViewIndicatorStyleWhite;
self.itemList.clipsToBounds = NO;
self.itemList.scrollEnabled = YES;
self.itemList.pagingEnabled = NO;
NSInteger tot=0;
CGFloat cx = 0;
for (; ; tot++) {
if (tot==12) {
break;
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[self.itemNames objectAtIndex:tot]]];
CGRect rect = imageView.frame;
rect.size.height = 40;
rect.size.width = 40;
rect.origin.x = cx;
rect.origin.y = 0;
imageView.frame = rect;
[self.itemList addSubview:imageView];
cx += imageView.frame.size.width;
}
[self.itemList setContentSize:CGSizeMake(cx, [self.itemList bounds].size.height)];
}
I have added the [self.itemList setTranslatesAutoresizingMaskIntoConstraints:NO]; because I saw this suggestion on other posts, but it doesn't work with or without it. The only way it works is if I uncheck use AutoLayout on the storyboard, but that moves the UIImageViewI use to look as a navigation bar to the bottom of the screen.
I don't know what to do anymore, any help is appreciated :)
Try to set your scrollView's Content size int "viewDidLayoutSubviews" method with keeping the autolayouts set.
-(void)viewDidLayoutSubviews
{
[self.itemList setContentSize:CGSizeMake(required_width, required_height)];
}
Two Solutions:
Create different constraints that can be satisfied simultaneously (you will have to edit). I think the problem is your bottom space and top space constraints are mutually exclusive. please remove one and try again. IF this is difficult for you, try adding another UIView to contain the UIScrollView to help manage your constraints, it might seem odd at first, but sometimes adding another view to contain your view actually makes it simpler at each level.
Turn off Autolayout, and change the autoresize masks of your UIImageView to be what you wish.
Insert: [scrollView setContentSize:CGSizeMake(x,y)]; in the following method:
-(void)viewWillAppear:(BOOL)animated

Scrolling UILabel like a marquee in a subview

I have a UILabel in the main view with text - "Very Very long text". The proper width to this would be 142, but i've shortened it to 55.
Basically I want to implement a marquee type scroll, so I wrote code to add it onto a subview and animate it within the bounds of that view.
CODE --
CGRect tempLblFrame = _lblLongText.frame;
UIView *lblView = [[UIView alloc] initWithFrame:tempLblFrame];
//Add label to UIView at 0,0 wrt to new UIView
tempLblFrame.origin.x = 0;
tempLblFrame.origin.y = 0;
[_lblLongText setFrame:tempLblFrame];
[_lblLongText removeFromSuperview];
[lblView addSubview:_lblLongText];
//SetClipToBounds so that if label moves out of bounds of its superview, it wont be displayed
[lblView setClipsToBounds:YES];
[lblView setBackgroundColor:[UIColor cyanColor]];
[self.view addSubview:lblView];
After this I get this output on the simulator -->
The problem occurs when i try the Animation with this code -
tempLblFrame.origin.x = -_lblLongText.intrinsicContentSize.width;
[UIView animateWithDuration:2.0 delay:1.0 options:UIViewAnimationOptionCurveLinear
animations:^{
[_lblLongText setFrame:tempLblFrame];
}
completion:^(BOOL finished) {
NSLog(#"completed");
}];
I was hoping I would see the entire "Very Very long text", rather only "Very..." scrolls from left to right.
To solve this I added one line of code --
//Add label to UIView at 0,0 wrt to new UIView
tempLblFrame.origin.x = 0;
tempLblFrame.origin.y = 0;
tempLblFrame.size.width = _lblLongText.intrinsicContentSize.width; //THIS LINE WAS ADDED
[_lblLongText setFrame:tempLblFrame];
[_lblLongText removeFromSuperview];
[lblView addSubview:_lblLongText];
I thought the full text will be set inside the newly added UIView and it would scroll properly. But running in the simulator gave me this --
And again, only "Very..." was scrolling from left to right.
What am I doing wrong? Please help!!
EDIT
Apparently the culprit was AutoLayout.
I have no clue why, but once I unchecked "Use Autolayout" for the view
in the XIB, everything started working as expected. Setting
tempLblFrame.origin.x = -_lblLongText.intrinsicContentSize.width; was
working properly and so was the scroll.
Any explanation on this!!?
This question is possibly Duplicate of.
Although there is nice code snippet written by Charles Powell for MarqueeLabel,
also take a look at This link.
I hope this will help you and will save your time by giving a desired output.
Make the UILabel the width (or longer) of the text and the UIView the scroll area you want to see. Then set the UIView's clipToBounds to YES (which you are doing). Then when you animate left to right you will only see the the text the width of the UIView, since it is cutting any extra subviews. Just make sure you scroll the entire length of the UILabel.
Right now you are setting the view and label's height and width to the same thing. This is why you are getting clipped text, not a clipped label.
You add In your view scrollview and add this label in your scroll view .Use this code
scroll.contentSize =CGSizeMake(100 *[clubArray count],20);
NSString *bname;
bname=#"";
for(int i = 0; i < [clubArray count]; i++)
{
bname = [NSString stringWithFormat:#"%# %# ,",bname,[[clubArray objectAtIndex:i] objectForKey:#"bottle_name"]];
[bname retain];
}
UILabel *lbl1 = [[UILabel alloc] init];
[lbl1 setFrame:CGRectMake(0,5,[clubArray count]*100,20)];
lbl1.backgroundColor=[UIColor clearColor];
lbl1.textColor=[UIColor whiteColor];
lbl1.userInteractionEnabled=YES;
[scroll addSubview:lbl1];
lbl1.text= bname;
This is implemented code.Thanks
Apparently the culprit was AutoLayout.
I have no clue why, but once I unchecked "Use Autolayout" for the view in the XIB, everything started working as expected. Setting tempLblFrame.origin.x = -_lblLongText.intrinsicContentSize.width; was working properly and so was the scroll.
Still, a better explanation for this would surely help!!
EDIT: Solution with AutoLayout -
//Make UIView for Label to sit in
CGRect tempLblFrame = _lblLongText.frame;
UIView *lblView = [[UIView alloc] initWithFrame:tempLblFrame];
//#CHANGE 1 Removing all constraints
[_lblLongText removeConstraints:_lblLongText.constraints];
//Add label to UIView at 0,0 wrt to new UIView
tempLblFrame.origin.x = 0;
tempLblFrame.origin.y = 0;
//Set Full length of Label so that complete text shows (else only truncated text will scroll)
tempLblFrame.size.width = _lblLongText.intrinsicContentSize.width;
//#CHANGE 2 setting fresh constraints using the frame which was manually set
[_lblLongText setTranslatesAutoresizingMaskIntoConstraints :YES];
[_lblLongText setFrame:tempLblFrame];
[_lblLongText removeFromSuperview];
[lblView addSubview:_lblLongText];

Resources