iOS: Keyboard freezes on device but works in simulator - ios

Whenever I go to enter text in a subclassed UITextfield on the device, I'll get two or three characters entered and then the app freezes. Can't dismiss the keyboard or touch any tabs. Here's the UITextField subclass:
#implementation OAI_TextField
#synthesize elementID;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
colorManager = [[OAI_ColorManager alloc] init];
fileManager = [[OAI_FileManager alloc] init];
self.font = [UIFont fontWithName:#"Helvetica" size:20.0];
self.textColor = [colorManager setColor:66.0 :66.0 :66.0];
self.borderStyle = UITextBorderStyleRoundedRect;
self.backgroundColor = [UIColor whiteColor];
self.returnKeyType = UIReturnKeyDone;
self.delegate = self;
}
return self;
}
#pragma mark Text Field Delegate Methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self resignFirstResponder];
//if project number text field we're going to check and see if the "Project" directory contains the file, if not we'll create it
//get super view
UIView* myParent = self.superview;
//get the subviews
NSArray* mySiblings = myParent.subviews;
//get the label
UILabel* myLabel = [mySiblings objectAtIndex:0];
//get the label text
NSString* myLabelText = myLabel.text;
//check it!
if ([myLabelText isEqualToString:#"Project Number:"]) {
NSString* projectNumberPlist = [NSString stringWithFormat:#"%#.plist", self.text];
NSString* projectNumberPlistPath = [NSString stringWithFormat:#"Projects/%#", projectNumberPlist];
[fileManager createFile:projectNumberPlist:projectNumberPlistPath];
}
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
NSLog(#"ok");
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#end
I'll get the NSLog call in - (void)textFieldDidBeginEditing:. I do not get any error messages in the console. Not really sure where to begin debugging this. Could someone give me a nudge?
Thanks

Related

Adding Subview to UICollectionViewCell Subclass?

I seem to be having trouble adding a subview to a view within my UICollectionViewCell subclass.
I have an abstract UICollectionViewCell subclass titled MessageItem, which looks like this:
I've created a few classes that inherit from this (since they all use the same logic for the header and footer). However I can't seem to add any subviews into MessageItem's blue view from within the child subclasses.
For example one of the child views is called TextItem. I'm trying to add a label to it's parent messageView (the blue view) but it only works if I do it in my UIViewController's cellForItemAtIndexPath:(NSIndexPath *)indexPath method, and not in my custom subclass.
This is how I'm trying to add it in my child subclass:
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
//Setup Message Label
[self setupMessageLabel];
}
return self;
}
#pragma mark - Setup Methods
- (void)setupMessageLabel {
NSLog(#"Setting up label");
//Setup Message Label
self.messageLabel = [TTTAttributedLabel new];
self.messageLabel.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
self.messageLabel.textInsets = UIEdgeInsetsMake(8, 8, 8, 8);
self.messageLabel.numberOfLines = 0;
[self.messageContentView addSubview:self.messageLabel];
[self.messageContentView autoPinEdgesToSuperviewEdges];
//Update Label Color
self.messageLabel.backgroundColor = FlatRed;
}
Note: I'm not using storyboard or xibs. Could that be the problem?
Update
This is what my MessageItem class is implemented:
MessageItem.h
#import <UIKit/UIKit.h>
#class Message;
#interface MessageItem : UICollectionViewCell
#property (nonatomic, strong) Message *message;
#property (nonatomic, strong) UIView *messageContentView;
#end
MessageItem.m
#interface MessageItem ()
#property (nonatomic, strong) TTTAttributedLabel *headerLabel;
#property (nonatomic, strong) TTTAttributedLabel *footerLabel;
#end
#implementation MessageItem
#synthesize message = _message;
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
//Setup Main View
[self setupMainView];
}
return self;
}
#pragma mark - Setup Methods
- (void)setupMainView {
//Setup Header
[self setupHeaderLabel];
//Setup Message
[self setupMessageView];
//Setup Footer View
[self setupFooterLabel];
}
- (void)setupHeaderLabel {
//Setup Header Label
self.headerLabel = [[TTTAttributedLabel alloc] initForAutoLayout];
self.headerLabel.font = [UIFont fontWithName:#"Lato-Bold" size:12.0];
self.headerLabel.textColor = FlatGray;
self.headerLabel.textAlignment = NSTextAlignmentCenter;
self.headerLabel.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
self.headerLabel.textInsets = UIEdgeInsetsMake(0, 8, 0, 8);
self.headerLabel.backgroundColor = FlatPurple;
[self.contentView addSubview:self.headerLabel];
[self.headerLabel autoSetDimension:ALDimensionHeight toSize:20.0];
[self.headerLabel autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeBottom];
}
- (void)setupMessageView {
//Setup Message View
self.messageContentView = [UIView new];
self.messageContentView.backgroundColor = [UIColor blueColor];
[self.contentView addSubview:self.messageContentView];
[self.messageContentView autoSetDimension:ALDimensionHeight toSize:30 relation:NSLayoutRelationGreaterThanOrEqual];
[self.messageContentView autoPinEdgeToSuperviewEdge:ALEdgeLeading];
[self.messageContentView autoPinEdgeToSuperviewEdge:ALEdgeTrailing];
[self.messageContentView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.headerLabel];
}
- (void)setupFooterLabel {
//Setup Footer Label
self.footerLabel = [[TTTAttributedLabel alloc] initForAutoLayout];
self.footerLabel.font = [UIFont fontWithName:#"Lato-Bold" size:10.0];
self.footerLabel.textColor = FlatGray;
self.footerLabel.backgroundColor = FlatGreen;
self.footerLabel.textAlignment = NSTextAlignmentLeft;
self.footerLabel.textInsets = UIEdgeInsetsMake(0, 8, 0, 8);
[self.contentView addSubview:self.footerLabel];
[self.footerLabel autoSetDimension:ALDimensionHeight toSize:10.0];
[self.footerLabel autoPinEdgeToSuperviewEdge:ALEdgeLeading];
[self.footerLabel autoPinEdgeToSuperviewEdge:ALEdgeTrailing];
[self.footerLabel autoPinEdgeToSuperviewEdge:ALEdgeBottom];
[self.footerLabel autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.messageContentView];
}
TextItem.m
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
//Setup Message Label
[self setupMessageLabel];
}
return self;
}
#pragma mark - Setup Methods
- (void)setupMessageLabel {
//Setup Message Label
self.messageLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
self.messageLabel.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
self.messageLabel.textInsets = UIEdgeInsetsMake(8, 8, 8, 8);
self.messageLabel.numberOfLines = 0;
[self.messageContentView addSubview:self.messageLabel];
//Update Label Color
self.messageLabel.backgroundColor = FlatRed;
}
#pragma mark - Setter Methods
- (void)setMessageText:(NSString *)text {
//Incoming Text Message
NSMutableAttributedString *textString = [[NSMutableAttributedString alloc] initWithString:text];
[textString addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(0, textString.length)];
[textString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16 weight:UIFontWeightLight] range:NSMakeRange(0, textString.length)];
//Set Paragraph Style
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.minimumLineHeight = 20;
paragraphStyle.maximumLineHeight = 20;
[textString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, textString.length)];
//Update Message Label
[self.messageLabel setText:textString];
NSLog(#"Set Message Label Text");
}
- (void)setMessage:(Message *)message {
//Super
[super setMessage:message];
//Update Message Text
[self setMessageText:message.text];
}
This is what my collectionView looks like:
I would at least expect the color of the messageLabel to reflect the change in TextItem, but it doesn't.
Have you implement initWithCoder?
- (id)initWithCoder:(NSCoder*)aDecoder
{
if(self = [super initWithCoder:aDecoder]) {
// Do something
}
return self;
}
I don't have all your code, but you code looks good to me. Maybe the problem was how you init the TextItem.
Here is a demo using your code, it works fine to me. https://www.dropbox.com/s/7qp9ayqnyacf57j/CustomCellView.zip?dl=0

Custom UIView getting display late

I'm facing an weird issue, I'm developing a iOS static library, this static library have some custom UIViews. These custom views contains UIButtons and IBOutlets for those buttons, Custom UIView has been create in Xib. Now this static library I'm including inside another static library and I'm attaching custom UIView
of library one in to UIViewController's UIView of static library two with -
[self.view addSubview:aCustomViewFromLibrary1];
So when I'm using Library 2 in to some product everything goes great but when code of adding custom UIView of static library one to static library two runs everything goes right but custom UIView appears late, about half a minutes late.
here is the code for one of the custom UIView in static library one...
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(!self){
return nil;
}
_otpTextField.delegate = self;
loadView()
_approveOtpBtn.layer.cornerRadius = 5;
NSLog(#"%#",[NSString stringWithFormat:#"%s", __PRETTY_FUNCTION__]);
viewFrame = frame;
CALayer *layer = self.layer;
layer.shadowOffset = CGSizeMake(1, 1);
layer.shadowColor = [[UIColor blackColor] CGColor];
layer.shadowRadius = 4.0f;
layer.shadowOpacity = 0.80f;
layer.shadowPath = [[UIBezierPath bezierPathWithRect:layer.bounds] CGPath];
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if(!self){
return nil;
}
loadView()
_approveOtpBtn.layer.cornerRadius = 5;
NSLog(#"%#",[NSString stringWithFormat:#"%s", __PRETTY_FUNCTION__]);
return self;
}
-(void) awakeFromNib{
NSLog(#"%#",[NSString stringWithFormat:#"%s", __PRETTY_FUNCTION__]);
_approveOtpBtn.layer.cornerRadius = 5;
}
// Approve OTP
-(IBAction)approveOtp:(UIButton *) aButton{
NSLog(#"%#",[NSString stringWithFormat:#"%s", __PRETTY_FUNCTION__]);
}
// minimize custome browser
-(IBAction)minimizeCB:(UIButton *) aButton{
NSLog(#"%#",[NSString stringWithFormat:#"%s", __PRETTY_FUNCTION__]);
}
- (void) RegenerateOTP:(UIButton *) aButton{
NSLog(#"%#",[NSString stringWithFormat:#"%s", __PRETTY_FUNCTION__]);
}
------UPDATE------
This is how I'm adding above custom View in the UIViewController's UIView.
- (void) updateView{
if([paymentOption isEqualToString:CHOOSE]){
if(_choose){
[_choose removeFromSuperview];
_choose = nil;
}
if(_approveOTP){
[_approveOTP removeFromSuperview];
_approveOTP = nil;
}
if(_regenOTPView){
[_regenOTPView removeFromSuperview];
_regenOTPView = nil;
}
_choose = [[CBAllPaymentOption alloc] initWithFrame:CGRectMake(0,self.resultView.frame.size.height - 227,self.resultView.frame.size.width,227)];
_choose.bankJS = _bankSpecificJavaScriptDict;
_choose.handler = self;
NSLog(#"loadJavascript AllOptionView view = %# ResultView = %#",_choose,_resultView);
//[_resultView addSubview:_choose];
if(_connectionHandlerDelegate && [_connectionHandlerDelegate respondsToSelector:#selector(addViewInResultView:)]){
[_connectionHandlerDelegate addViewInResultView:_choose];
}
[_resultView bringSubviewToFront:_choose];
// view getting display late so call setNeedDisplay.
[_choose setNeedsDisplay];
_choose.isViewOnScreen = YES;
}
}
Any solution and suggestion are welcome
Any changes you make to the UI must be done on the main thread.
You can try something like this.
dispatch_async(dispatch_get_main_queue(), ^{
// perform updates here
});

Misplaced view warning and odd behavior with IB_DESIGNABLE custom view using auto layout

I create a custom IB-designable view (see code below) which renders correctly in IB and also works fine when running it. However, in get this warning about the view being misplaced and I cannot manually resize the view in Interface Builder (when touching a resize handle, the view will jump around in its container).
I get the same or similar behavior for all kinds of different layouts. Do you have an idea if I'm doing something wrong here, or is this just a bug in IB?
(PS: I cannot just ignore the warning)
EDIT: added screenshot of constraints:
Here is the code (header):
IB_DESIGNABLE
#interface AKATestView : UIView
#end
Implementation:
#interface AKATestView()
#property(nonatomic)BOOL subviewsCreated;
#property(nonatomic)BOOL subviewConstraintsCreated;
#property(nonatomic)NSDictionary* views;
#end
#implementation AKATestView
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self setupAfterInit];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupAfterInit];
}
return self;
}
- (void)setupAfterInit
{
[self createSubviews];
}
- (void)createSubviews
{
if (!self.subviewsCreated)
{
self.translatesAutoresizingMaskIntoConstraints = NO;
UILabel* labelView = [[UILabel alloc] initWithFrame:CGRectZero];
labelView.text = #"Name";
labelView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:labelView];
UITextField* textField = [[UITextField alloc] initWithFrame:CGRectZero];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.placeholder = #"Enter some text";
textField.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:textField];
UILabel* errorMessageLabel = [[UILabel alloc] initWithFrame:CGRectZero];
errorMessageLabel.text = #"Error message";
errorMessageLabel.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:errorMessageLabel];
self.views = #{ #"label": labelView, #"editor": textField, #"errorMessageLabel": errorMessageLabel };
self.subviewsCreated = YES;
[self setNeedsUpdateConstraints];
}
}
- (void)updateConstraints
{
if (!self.subviewConstraintsCreated)
{
NSDictionary* metrics =
#{ #"pt": #(4), #"pr": #(4), #"pb": #(4), #"pl": #(4),
#"labelWidth": #(100),
#"errorPl": #(4 + 100 + 4),
#"hsLabelEditor": #(4), #"vsEditorError": #(2)
};
NSArray* specs =
#[ #{ #"format": #"H:|-(pl)-[label(labelWidth)]-(hsLabelEditor)-[editor]-(pr)-|",
#"options": #(NSLayoutFormatAlignAllFirstBaseline) },
#{ #"format": #"V:|-(pt)-[editor]-(vsEditorError)-[errorMessageLabel]-(pb)-|",
#"options": #(NSLayoutFormatAlignAllLeading|NSLayoutFormatAlignAllTrailing) }
];
for (NSDictionary* spec in specs)
{
NSString* format = spec[#"format"];
NSUInteger options = ((NSNumber*)spec[#"options"]).unsignedIntegerValue;
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:format
options:options
metrics:metrics
views:self.views];
[self addConstraints:constraints];
}
self.subviewConstraintsCreated = YES;
}
[super updateConstraints];
}
#end
Try removing self.translatesAutoresizingMaskIntoConstraints = NO; in your createSubviews method. IB seems to be relying on this translation to come up with correct measurement on the designer. I had the exact same problem and this fixed it.
I still have translatesAutosizingMaskIntoConstraints to NO for subviews. I confirmed that there aren't any extra constraints generated even with this set to YES. Hope it's the case for you too!

Create UITextField on UIView but can not get text input

I am using Xcode 6 and doing a small project on iOS 8, and I need to render some text onto the View.
My method is to create a UITextField on a UIView and as long as people type onit, the app redraw the View:
- (void)viewDidLoad {
[super viewDidLoad];
self.renderTextView.textToRender = #"Please type something…";
UITextField* textField = [[UITextField alloc] initWithFrame:self.renderTextView.frame];
textField.opaque = NO;
[self.renderTextView addSubview:textField];
[textField addTarget:self action:#selector(updateLabelAndRefresh:) forControlEvents:UIControlEventEditingChanged];
}
- (void) updateLabelAndRefresh: (id)sender{
self.renderTextView.textToRender = #"Hello World";
// if text's length > 0 …
if (self.textField.text.length > 0) {
self.renderTextView.textToRender = self.textField.text;
}
[self.renderTextView setNeedsDisplay];
}
But the problem is: no matter how I try, I can not get the actual text I type on my phone. and the console showed me that the text is null. I kept googling it but I stil can not work it out.
Do you guys have any solution? Thank you ;)
In below some error is there, give a look.
- (void)viewDidLoad {
[super viewDidLoad];
//Here textField is local variable
UITextField* textField = [[UITextField alloc] initWithFrame:self.renderTextView.frame];
textField.opaque = NO;
}
- (void) updateLabelAndRefresh: (id)sender{
self.renderTextView.textToRender = #"Hello World";
// if text's length > 0 …
if (self.textField.text.length > 0) { //Then how come u getting self.textField here and using it as global one.
//So you won't get access to that locally defined textField in viewDidLoad method.
self.renderTextView.textToRender = self.textField.text;
}
}
Please check your code and update me about it.

Displaying a single string in a view programmatically on iOS

We have a window filled with little view squares (think of a Calculator).
For a specific view on the window we want display a single string in the view without using the Interface Builder to add the string.
We need to be able to change the string and have the view refresh.
How do we programmatically add a string to a view and show it?
Update:
Ok here is the code we have currently. Nothing special in the header file.
I suppose the real quandry is considering we can easily get the background color to change, why is it that our text is just not showing??
Both versions are in there, would be happy to get 'apples' or 'oranges' displaying.
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
bgString = #"orange";
UILabel* aLabel = [[UILabel alloc] init];
aLabel.text = #"apple";
self.textLabel = aLabel;
[aLabel release];
[self addSubview:textLabel];
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
[[UIColor yellowColor] setFill];
UIRectFill(rect);
[self drawStringCenteredIn:rect];
}
- (void)drawStringCenteredIn:(CGRect)r {
//CGSize strSize = [bgString size];
CGPoint strOrigin;
strOrigin.x = r.origin.x; //+ (r.size.width - 10)/2;
strOrigin.y = r.origin.y; //+ (r.size.height - 10)/2;
//[bgString drawAtPoint:strOrigin withFont:[UIFont fontWithName:#"Helvetica" size:10]];
[textLabel drawTextInRect:r];
}
In your view controller's .h:
#interface MyViewController
{
UILabel* label;
}
#property (nonatomic, retain) UILabel* label;
In your view controller's .m:
- (void)dealloc
{
[label release];
[super dealloc];
}
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel* aLabel = [[UILabel alloc] init];
aLabel.text = #"Initial Text";
self.label = aLabel;
[aLabel release];
[self.view addSubview:aLabel];
}
- (void)viewDidUnload
{
[self.label removeFromSuperview];
self.label = nil;
}
// Call this when you need to update the label
- (void)updateLabel
{
self.label.text = #"Some updated text";
}
Did that from memory but it should work.
Try this:
UILabel* aLabel = [[UILabel alloc] initWithFrame:[self bounds]];
If you are creating the label manually, you need to set it's frame manually too.
Frame itself is size and position inside parent view(superview).
In my example i've set the frame of label to occupy the entire view. If you need your custom size you can use:
UILabel* aLabel = [[UILabel alloc] initWithFrame:CGRectMake(x,y,width,height)];
Where (x,y) - position of the top left corner of your label.
How about creating a UILabel and adding it to the view?
If you subclass the UIView, you can draw your string in the view's drawRect. This allows great flexibility in modifying the text, its appearance, and its placement (you can even animate it around, spin, rotate, etc.)
Call setNeedsDisplay on the view after you change your NSString. Then do an drawAtPoint:withFont: on the NSString when the drawRect is called.

Resources