I have this code to embed font to all text field on all UIView :
for (UIView *subview in [[self view] subviews]) {
if ([subview isKindOfClass:[UITextField class]]) {
UITextField *textField = (UITextField *)subview;
[textField setFont:[UIFont fontWithName:#"ABeeZee-Regular" size:14]];
}
}
but, it's just embedding font to text field and it will do to all UIView. on the other hand, I want to create some method to specific UIView, so I decided to add each UIView on my interface file :
#property (strong, nonatomic) IBOutlet UIView *viewOne;
#property (strong, nonatomic) IBOutlet UIView *viewTwo;
#property (strong, nonatomic) IBOutlet UIView *viewThree;
now, how to create for loop to 'select' all UI components (button, label, textfield, etc) on (let's say) UIView viewOne, so that I can create method to it? for example, changing all component alpha = 0?
thank you.
How about this:
for (UIView *subview in self.viewOne.subviews) {
if ([subview respondsToSelector:#selector(setAlpha:)])
subview.alpha = 0;
}
Related
When using JSQMessagesViewController as detailView in UISplitViewController, KeyBoardToolBar needs to appear in DetailViewController only
late answer...
if u want to reduce the inputToolbar you need to create a subclass of JSQMessagesToolbarContentView and provide your own view for the tool bar's content view.
below i am giving the sample example, create a subcalss of JSQMessagesToolbarContentView name it as JSQMessagesToolbarContentView_custom in the subcalss add below code,
#import "JSQMessagesToolbarContentView.h"
#interface JSQMessagesToolbarContentView_custom : JSQMessagesToolbarContentView
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *holderViewLeadingConstraint;
#end
and in JSQMessagesToolbarContentView_custom.m file,
#import "UIView+JSQMessages.h"
#import "JSQMessagesToolbarContentView_custom.h"
#implementation JSQMessagesToolbarContentView_custom
+ (UINib *)nib
{
return [UINib nibWithNibName:NSStringFromClass([JSQMessagesToolbarContentView_custom class])
bundle:[NSBundle bundleForClass:[JSQMessagesToolbarContentView_custom class]]];
}
#pragma mark - Initialization
- (void)awakeFromNib
{
[super awakeFromNib];
[self setTranslatesAutoresizingMaskIntoConstraints:NO];
self.backgroundColor = [UIColor clearColor];
}
//below method will place the contentview to desired position
- (void)layoutSubviews
{
[super layoutSubviews];
self.holderViewLeadingConstraint.constant = 320;
}
#pragma mark - Setters
- (void)setBackgroundColor:(UIColor *)backgroundColor
{
[super setBackgroundColor:backgroundColor];
self.leftBarButtonContainerView.backgroundColor = backgroundColor;
self.rightBarButtonContainerView.backgroundColor = backgroundColor;
}
- (void)setLeftBarButtonItem:(UIButton *)leftBarButtonItem
{
[super setLeftBarButtonItem:leftBarButtonItem];
}
- (void)setLeftBarButtonItemWidth:(CGFloat)leftBarButtonItemWidth
{
// self.leftBarButtonContainerViewWidthConstraint.constant = leftBarButtonItemWidth;
[self setNeedsUpdateConstraints];
}
- (void)setRightBarButtonItem:(UIButton *)rightBarButtonItem
{
[super setRightBarButtonItem:rightBarButtonItem];
}
- (void)setRightBarButtonItemWidth:(CGFloat)rightBarButtonItemWidth
{
// self.rightBarButtonContainerViewWidthConstraint.constant = rightBarButtonItemWidth;
[self setNeedsUpdateConstraints];
}
- (void)setRightContentPadding:(CGFloat)rightContentPadding
{
// self.rightHorizontalSpacingConstraint.constant = rightContentPadding;
[self setNeedsUpdateConstraints];
}
- (void)setLeftContentPadding:(CGFloat)leftContentPadding
{
// self.leftHorizontalSpacingConstraint.constant = leftContentPadding;
[self setNeedsUpdateConstraints];
}
#pragma mark - UIView overrides
- (void)setNeedsDisplay
{
[super setNeedsDisplay];
[self.textView setNeedsDisplay];
}
//return the custom view that we are going to create next
- (JSQMessagesToolbarContentView_custom *)loadToolbarContentView
{
NSArray *nibViews = [[NSBundle bundleForClass:[JSQMessagesToolbarContentView_custom class]] loadNibNamed:NSStringFromClass([JSQMessagesToolbarContentView_custom class]) owner:nil options:nil];
return nibViews.firstObject;
}
after this you need to create add new .xib file name it as JSQMessagesToolbarContentView_custom.xib this file contains our small content view for the inputToolbar and more importantly set the out let connections as doing the demo example and aslo set the view class name to JSQMessagesToolbarContentView_custom. hear i can only add image of the custom view.
now create a outlet for leading constraint to reduce the size of the content view as give below,
and add the constraints outlet's as given in the demo. so if u add some constrians without modifying the base class it will give error or runtime error so edit the base class also
now go to JSQMessagesToolbarContentView.h and add the blow properties form JSQMessagesToolbarContentView.m just cut and past and make it public.
#interface JSQMessagesToolbarContentView : UIView
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftBarButtonContainerViewWidthConstraint;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightBarButtonContainerViewWidthConstraint;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftHorizontalSpacingConstraint;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightHorizontalSpacingConstraint;
//...rest of the code
now in the JSQMessagesInputToolbar.m file, in order to make the tool bar transperent for half of the splitview,
- (void)awakeFromNib
{
[super awakeFromNib];
//...rest of the code
[self setBackgroundImage:[UIImage new]//imageNamed:#"topbar"]
forToolbarPosition:UIToolbarPositionAny
barMetrics:UIBarMetricsDefault];
[self setShadowImage:[UIImage new] forToolbarPosition:UIBarPositionAny];
[self setBackgroundColor:[UIColor clearColor]];
}
thats it now run the project, and change the leading constraints constant you see below output,
I'm trying to hide a UIView and objects within it when a button is deselected. The button is located in a TableView section header contained in the same ViewController.
The button press is being stored in...
Activity.h
#property BOOL invitesAll;
Activity.m
#import "Activity.h"
#dynamic invitesAll;
And the rest of the code...
InviteContactsViewController.h
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *expirationViewHeightConstraint;
#property (weak, nonatomic) IBOutlet UILabel *timeToRespondLabel;
#property (weak, nonatomic) IBOutlet UISlider *expirationSlider;
#property (weak, nonatomic) IBOutlet UILabel *expirationLabel;
#property (strong, nonatomic) IBOutlet UIButton *inviteAll;
InviteesTableViewController.h
#import "InviteContactsViewController.h"
#property (weak, nonatomic) NSLayoutConstraint *expirationViewHeightConstraint;
#property (weak, nonatomic) UILabel *timeToRespondLabel;
#property (weak, nonatomic) UISlider *expirationSlider;
#property (weak, nonatomic) UILabel *expirationLabel;
InviteesTableViewController.m
#import "InviteesTableViewController.h"
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// create button
InviteAllButton *inviteAllButton = [InviteAllButton buttonWithType:UIButtonTypeCustom];
[inviteAllButton setTitle:#"Order Matters" forState:UIControlStateSelected];
[inviteAllButton setTitle:#"Order Doesn't Matter" forState:UIControlStateNormal];
inviteAllButton.titleLabel.font = [UIFont fontWithName:#"Avenir" size:11.0];
inviteAllButton.titleLabel.numberOfLines = 2;
[inviteAllButton addTarget:self action:#selector(inviteAllAction:) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:inviteAllButton];
// set inviteAll button state
inviteAllButton.selected = !_activity.invitesAll;
// set constraints
[inviteAllButton setTranslatesAutoresizingMaskIntoConstraints:NO];
NSDictionary *views = NSDictionaryOfVariableBindings(inviteAllButton, titleLabel);
[headerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"[titleLabel]-(>=5)-[inviteAllButton(96)]-5-|" options:0 metrics:nil views:views]];
[headerView addConstraint:[NSLayoutConstraint constraintWithItem:inviteAllButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:headerView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
}
- (void)inviteAllAction:(UIButton *)sender {
sender.selected = !sender.selected;
_activity.invitesAll = !_activity.invitesAll;
[self validateReordering];
[self.tableView reloadData];
NSString *state = _activity.invitesAll ? #"invitesAll" : #"orderMatters";
// In my attempt to hide the view, I've set an expirationViewHeightConstraint
// and try to change its constant as the button is pressed
if (self.activity.invitesAll) {
self.expirationViewHeightConstraint.constant = 0.f;
self.timeToRespondLabel.hidden = YES;
self.expirationSlider.hidden = YES;
self.expirationLabel.hidden = YES;
} else {
self.expirationViewHeightConstraint.constant = 35;
self.timeToRespondLabel.hidden = NO;
self.expirationSlider.hidden = NO;
self.expirationLabel.hidden = NO;
}
}
I referenced Max's answer on changing the height constraint constant to 0.f and tried to follow Simon's answer on accessing properties across ViewControllers as a basis, but to no avail. When I run this nothing visible happens with the expirationViewHeightConstraint, timeToRespondLabel, expirationSlider, or expirationLabel IBOutlets when inviteAll is pressed.
I'm a newb so guessing I'm missing something basic here. Is my approach flawed?
What you're doing with the property declarations in InviteesTableViewController is wrong. You can't just declare some properties in the child controller and expect that they will point to objects in some other controller (parent or not). You need to get a reference to the parent, which you can using self.parentViewController, and then access its properties with that,
InviteContactsViewController *inviteVC = (InviteContactsViewController *)self.parentViewController;
if (self.activity.invitesAll) {
inviteVC.expirationViewHeightConstraint.constant = 0.f;
inviteVC.timeToRespondLabel.hidden = YES;
inviteVC.expirationSlider.hidden = YES;
inviteVC.expirationLabel.hidden = YES;
} else {
inviteVC.expirationViewHeightConstraint.constant = 35;
inviteVC.timeToRespondLabel.hidden = NO;
inviteVC.expirationSlider.hidden = NO;
inviteVC.expirationLabel.hidden = NO;
}
You should delete all those property declarations in InviteesTableViewController.
I have the following code in a view controller:
#interface QuizController ()
#property (weak, nonatomic) IBOutlet UITextView *questionText;
#property (weak, nonatomic) IBOutlet UITextView *one;
#property (weak, nonatomic) IBOutlet UITextView *two;
#property (weak, nonatomic) IBOutlet UITextView *three;
#property (weak, nonatomic) IBOutlet UITextView *four;
#property(strong, nonatomic) NSMutableArray* possAnswers;
#end
#implementation QuizController
- (void)viewDidLoad {
[super viewDidLoad];
[self.manager setupGame];
self.possAnswers = [[NSMutableArray alloc] initWithObjects:#"a", #"b", #"c", #"d", nil];
}
//This listens for a tap on any of the TextViews and sets the background to Blue
- (IBAction)fourTapped:(id)sender {
NSLog(#"There's been a tap!");
[self blankBoxes];
if( [sender isKindOfClass:[UITapGestureRecognizer class]] )
{
UITapGestureRecognizer* tgr = (UITapGestureRecognizer*)sender;
UIView* view = tgr.view;
if( [view isKindOfClass:[UITextView class]]){
UITextView* tv = (UITextView*)view;
NSLog([tv text]);
[tv setBackgroundColor:[UIColor blueColor]];
}
}
}
-(void)blankBoxes
{
[_one setBackgroundColor:[UIColor whiteColor]];
[_two setBackgroundColor:[UIColor whiteColor]];
[_three setBackgroundColor:[UIColor whiteColor]];
[_four setBackgroundColor:[UIColor whiteColor]];
}
However, the only UITextView that gets highlighted is _one, no matter which view is tapped. I don't understand why this is. I'd be really grateful if anyone could point this out to me.
Gesture recognizers attach to one and only one view. That's by design. If you want a single gesture recognizer that lets you recognize taps on multiple views, you have to attach it to a common, enclosing superview, then look at the tap coordinates and figure out which view was tapped.
Normally you just create a different gesture recognizer for each view that needs to responds to taps.
Add the UIGestureRecognizer to a UIView that contains your subviews. After that use CGRectContainsPoint() to check if the tap location is in one of the subviews, then continue from there.
CGPoint *touchLocation = [gesture locationInView:self];
for(UIView *view in self.subviews){
if(CGRectContainsPoint(view.frame, touchLocation))
//Your code here
}
I would like to start by saying that I am fairly new to iOS programming, so excuse my ignorance.
I have three UITextFields in my CustomLayout. I am asking users to fill in their name, age and sex. I would like two things, if possible. First I would like, as soon as a user hits the return button from the keyboard, the input string to be stored in an NSArray. In addition, the secondary objective is to iterate through the UITextFields when the user hits the same button.
// CustomLayout.h
#interface CustomLayout : UIView {
UITextField *nameField;
UITextField *ageField;
UITextField *sexField;
UILabel *nameLabel;
UILabel *ageLabel;
UILabel *sexLabel;
UIButton *startButton;
}
#property (nonatomic, strong) UITextField *nameField;
#property (nonatomic, strong) UITextField *ageField;
#property (nonatomic, strong) UITextField *sexField;
#property (nonatomic, strong) UILabel *nameLabel;
#property (nonatomic, strong) UILabel *ageLabel;
#property (nonatomic, strong) UILabel *sexLabel;
#property (nonatomic, strong) UIButton *startButton;
-(void)textFieldShouldReturn:(UITextField*)textField;
#end
In the implementation file
//CustomLayout.m
#implementation CustomLayout
#synthesize nameField, ageField, sexField;
#synthesize nameLabel, ageLabel, sexLabel;
#synthesize startButton;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setBackgroundColor:[tkStyle viewBackgroundColor]];
NSString *startButtonLabel = #"Start Experiment";
//alocate and position views
CGRect viewRect;//placeholder rect, reused for each view
//nameLabel and nameField
nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 95, 150, 40)];
nameLabel.textColor = [UIColor colorWithRed:106/256.0 green:180/256.0 blue:150/256.0 alpha:1.0];
nameLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:25];
nameLabel.backgroundColor=[tkStyle viewBackgroundColor];
nameLabel.text=#"Enter Name:";
nameField = [[UITextField alloc] initWithFrame:CGRectMake(280, 90, 200, 40)];
nameField.textColor = [UIColor colorWithRed:0/256.0 green:84/256.0 blue:129/256.0 alpha:1.0];
nameField.font = [UIFont fontWithName:#"Helvetica-Bold" size:25];
nameField.borderStyle = UITextBorderStyleRoundedRect;
nameField.backgroundColor=[tkStyle viewBackgroundColor];
textFieldShouldReturn:nameField.text;
// same for ageField and sexField
//startButton
viewRect = CGRectMake(250, sexField.frame.origin.y+75, 200, 40);
startButton = [[UIButton alloc] initWithFrame:viewRect];
[startButton setTitle:startButtonLabel forState:UIControlStateNormal];
[startButton setTitleEdgeInsets:UIEdgeInsetsMake(4, 0, 0, 0)];
[startButton setButtonIsActive:true];
//[startButton setOSCAddress:OSCStopPressedString];
[startButton addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchDown];
//and so on adjust your view size according to your needs
[self addSubview:nameField];
[self addSubview:ageField];
[self addSubview:sexField];
[self addSubview:nameLabel];
[self addSubview:ageLabel];
[self addSubview:sexLabel];
[self addSubview:startButton];
}
return self;
}
// that should allow for users to hit 'return' button to move through textfields
-(void)textFieldShouldReturn:(UITextField*)textField;
{
//[(NSArray *) userInfoArray addObject:textField.text];
}
// that should change Views as soon as the user presses 'Start Experiment'
-(void)buttonAction:(id)sender
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"startTest" object:self];
}
#end
Any help would be appreciated.
NSDictionary will be a good approach. you can have unique key for each textfield value.
-(void)textFieldShouldReturn:(UITextField*)textField;
should be:
- (BOOL)textFieldShouldReturn:(UITextField*)textField;
Also, don't forget to return TRUE or FALSE (or YES or NO).
To make this work, implement the UITextFieldDelegate protocol in your class.
Put the following line of code in your .m file, above the #implementation:
#interface CustomLayout () <UITextFieldDelegate>
#end
then, set the delegate in your UITextFields with:
nameField.delegate = self;
ageField.delegate = self;
sexField.delegate = self;
This way the textFieldShouldReturn: method will be called when the user presses 'enter'
A couple of things:
Given your delegate methods, I assume you've actually specified the delegate for your three UITextField controls to be the object in which you've implemented these various delegate methods.
If you want to control the behavior of the return key, implement the textFieldShouldReturn method:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == self.nameField) {
[self.ageField becomeFirstResponder];
} else if (textField == self.ageField) {
[self.sexField becomeFirstResponder];
} else if (textField == self.sexField) {
[textField resignFirstResponder];
[self saveResults];
}
return NO;
}
I'd generally be inclined to do something like the above, where pressing return takes me to the next field, and pressing return on the last one dismisses the keyboard and tries to save the results.
BTW, in IB, I'd make sure that the "return key" setting for the first two control would be "Next", and for the last one, either "Go" or "Done".
Your save routine would simply populate an object with the contents of the three controls:
- (void)saveResults
{
Person *person = [[Person alloc] init];
person.name = self.nameField.text;
if (self.ageField.text) {
person.age = #([self.ageField.text integerValue]);
}
person.sex = self.sexField.text;
// now do whatever you want with this object
}
This obviously assumes that you have a Person class:
#interface Person : NSObject
#property (nonatomic, copy) NSString *name;
#property (nonatomic, strong) NSNumber *age;
#property (nonatomic, copy) NSString *sex;
#end
#implementation Person
#end
If you'd rather use a NSDictionary or NSArray, that's fine, too (make sure you check the text fields are not nil, though), though I personally prefer a well-defined model object like above.
As a refinement, you might want to make sure you only enter numeric values for age (if that's how you want to store the age):
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.ageField) {
NSCharacterSet *invalid = [[NSCharacterSet characterSetWithCharactersInString:#"1234567890"] invertedSet];
NSRange range = [string rangeOfCharacterFromSet:invalid];
return range.location == NSNotFound; // if non-numeric character not found, return true
}
return YES;
}
I'm trying to create a simple popup called Add Notes on a button click which has a save and cancel button to save the notes created by the user and to cancel the pop-up. This is pop-up classes
AddNotesPopUp.h
#import <UIKit/UIKit.h>
#import "UIImage+Buttons.h"
typedef enum AddNotesViewType
{
AddNotesPopUpSimple
}AddNotesPopUpType;
#protocol AddNotesDelegate<NSObject>
#optional
-(void)saveButtonClicked:(id) popUp;
-(void)cancelAddButtonClicked:(id)popUp;
#end
#interface AddNotesPopUp : UIView
#property AddNotesPopUpType atype;
#property (nonatomic,assign) id <AddNotesDelegate> delegate;
-(id)initWithDelegate:(id)parent type:(AddNotesPopUpType) type;
#property (weak, nonatomic) IBOutlet UIView *popView;
#property (strong, nonatomic) IBOutlet UIButton *titleButton;
#property (weak, nonatomic) IBOutlet UIButton *cancelAddButton;
#property (weak, nonatomic) IBOutlet UIButton *saveButton;
#property (weak, nonatomic) IBOutlet UITextView *textArea;
- (IBAction)saveButtonAction:(id)sender;
- (IBAction)cancelButtonAction:(id)sender;
-(void)show;
-(void)hide;
#end
AddNotesPopUp.m
#import "AddNotesPopUp.h"
#import <QuartzCore/QuartzCore.h>
#implementation AddNotesPopUp
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self=(AddNotesPopUp*)[[[NSBundle mainBundle] loadNibNamed:#"AddNotesPopUp" owner:nil options:nil] lastObject];
}
return self;
}
-(id)initWithDelegate:(id)parent type:(AddNotesPopUpType) type
{
if (self = [super initWithFrame:CGRectMake(0, 0, 300, 300)])
{
// Initialization code
self=(AddNotesPopUp*)[[[NSBundle mainBundle] loadNibNamed:#"AddNotesPopUp" owner:nil options:nil] lastObject];
}
self.delegate=parent;
self.atype=type;
UIViewController *parentView=(UIViewController*)parent;
[parentView.view addSubview:self];
if (type==AddNotesPopUpSimple)
{
[self.titleButton setImage:[UIImage buttonWithText:#"Add Notes" fontSize:15 bold:YES buttonSize:self.titleButton.frame.size baseColor:[UIColor colorWithRed:73.0/255.0 green:90.0/255.0 blue:100.0/255.0 alpha:1] downTo:[UIColor colorWithRed:57.0/255.0 green:70.0/255.0 blue:77.0/255.0 alpha:1]] forState:UIControlStateNormal];
[self.saveButton setImage:[UIImage buttonWithTextAlignCenter:#"Save" fontSize:15 bold:YES buttonSize:self.saveButton.frame.size baseColor:[UIColor colorWithRed:117.0/255.0 green:185.0/255.0 blue:83.0/255.0 alpha:1] downTo:[UIColor colorWithRed:95.0/255.0 green:144.0/255.0 blue:64.0/255.0 alpha:1]] forState:UIControlStateNormal];
[self.cancelAddButton setImage:[UIImage buttonWithTextAlignCenter:#"Cancel" fontSize:15 bold:YES buttonSize:self.cancelAddButton.frame.size baseColor:[UIColor colorWithRed:174.0/255.0 green:174.0/255.0 blue:174.0/255.0 alpha:1] downTo:[UIColor colorWithRed:124.0/255.0 green:124.0/255.0 blue:124.0/255.0 alpha:1]] forState:UIControlStateNormal];
}
self.popView.layer.masksToBounds=YES;
self.popView.layer.cornerRadius=5.0f;
self.popView.layer.borderWidth=1.0f;
self.popView.layer.borderColor=[[UIColor blackColor]CGColor];
self.popView.hidden=YES;
self.hidden=YES;
self.textArea.hidden=YES;
return self;
}
-(void)show
{
self.popView.hidden=NO;
self.textArea.hidden=NO;
[self.popView setTransform:CGAffineTransformMakeScale(0.1,0.1)];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
[self.popView setTransform:CGAffineTransformMakeScale(1.0,1.0)];
[UIView commitAnimations];
}
-(void) hide
{
self.popView.hidden=YES;
}
- (IBAction)saveButtonAction:(id)sender {
[self.delegate saveButtonClicked:self];
}
- (IBAction)cancelButtonAction:(id)sender {
[self.delegate cancelAddButtonClicked:self];
}
#end
This is how I call the popup in my viewcontroller button action
- (IBAction)addNotes:(id)sender {
AddNotesPopUp *pop=[[AddNotesPopUp alloc] initWithDelegate:self type:AddNotesPopUpSimple];
[pop show];
}
I have checked with breakpoints and the execution goes successfully through the initwithDelegate and show methods in AddNotesPopUp.m but the pop-up doesnt appears, what am I missing here? I have added the delegates and classes of AddNotesPopUp in my viewcontroller and I dont receive any error either. I'm using Xcode 4.6. Any Suggestions?
Turns out it was a simple issue, I just needed to add
self.hidden=NO; in the show method