how to create BOOL property for UIButton for checked selecting - ios

I create many button with loop from array but I want when click on any button I could check select state this button with one bool property with name : Selected.
when any button that I click on it selected change background to red color and when deselected change background to blue color.
please guide me how to create one property for any button.
this is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSMutableArray *arrayString = [[NSMutableArray alloc]initWithObjects:#"Mohammad",#"Hamidreza",#"Ahmad",#"Amirhossein",#"javad",#"asdasddasdsdasd", nil];
UIFont *myFont = [UIFont fontWithName:#"Helvetica" size:20];
CGFloat x = 5;
CGFloat y = 80;
for (NSString *text in arrayString) {
UIButton *button = [[UIButton alloc]init];
CGFloat width = [self widthOfString:text withFont:myFont];
CGFloat height = [self heightOfString:text withFont:myFont];
if ((x + width) > 320) {
NSLog(#"after line");
x = 5;
y += (height+20)+10;
button.frame = CGRectMake(x, y, width+20, height+20);
[button setTitle:text forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
x += (width+20)+10;
}
else {
NSLog(#"this line");
button.frame = CGRectMake(x, y, width+20, height+20);
[button setTitle:text forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
x += (width+20)+10;
}
[button addTarget:self action:#selector(Selected:) forControlEvents:UIControlEventTouchUpInside];
}
}
-(IBAction)Selected:(id)sender{
if (//check sender button property bool selected) {
}
else {
}
}

Try this code:-
- (void)viewDidLoad
{
[super viewDidLoad];
[self.button setBackgroundImage:[self imageWithColor:[UIColor redColor]]forState:(UIControlStateHighlighted)];
[self.button setBackgroundImage:[self imageWithColor:[UIColor redColor]]forState:(UIControlStateSelected)];
[self.button setBackgroundImage:[self imageWithColor:[UIColor blueColor]] forState:(UIControlStateNormal)];
}
- (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

Please, name your method starting with a lowercase. That's not related to your issue, but that's convention.
Since your question is more about "How do I get the button that was touched ?", than actually do your thing:
-(IBAction)selected:(id)sender //may rename this method to, it's quite strange, look like a "state/getter"
{
UIButton *button = (UIButton *)sender;
//Do something
if ([[button backgroundColor] isEqual:[selectedColor]])
{
//Do something
}
else
{
//Do something
}
}

my dude try this :
you don't need to create property for UIButton for this. you can do it with this code:
-(IBAction)Selected:(id)sender{
UIButton *button = (UIButton *)sender;
if (!button.selected) {
button.backgroundColor = [UIColor blueColor];
button.selected = YES;
}
else{
button.backgroundColor = [UIColor redColor];
button.selected = NO;
}
}
this code working for any button that you created!!! :D

Related

getting element from array one by one and createbutton

I have a UItextFeild as search bar on clicking a tableview with suggestion open.now i want to click on that row and make a button with its label in below view as described in image .how can i acheive this
I want it one by one means when i click on row it create a button on view and UITableView hide then again i start searching and on again clicking on some other row make a button with different value of X.
_selectednames = [NSMutableArray arrayWithCapacity:self.sortedArray.count];
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// MGContactItemsModel *model = _arrayForContacts[indexPath.row];
self.searchText.text = [NSString stringWithFormat:#"%#",[_sortedArray objectAtIndex:indexPath.row]];
self.tableView.hidden = YES;
[_selectednames addObject:_searchText.text];
for (int i; i < _selectednames.count ; i++) {
[self makeLabelsAndButtons:i];
}
now in my makeLabelsAndButtons funtion i done something like this
CGFloat xOffset = 10.0f;
int buttonCount = 0;
CGRect buttonFrame = CGRectMake(xOffset, 10.0, 50.0, 15.0);
NSString *nameString = [self.selectednames objectAtIndex:indexPath];
UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
//_button.frame = CGRectMake(xOffset, 10.0, 50.0, 15.0);
for(int i=buttonCount; i >0;i++) {
xOffset = xOffset+10;
buttonFrame.origin.x += buttonFrame.size.width+xOffset;
}
_button.frame = buttonFrame;
buttonCount++;
_button.tag = indexPath;
//button.center = CGPointMake(xOffset, 10.0f);
//[button setBackgroundImage:[UIImage imageNamed:picString] forState: UIControlStateNormal];
[_button setTitle:self.selectednames[indexPath] forState:UIControlStateNormal];
_button.backgroundColor = [UIColor lightGrayColor];
_button.titleLabel.font = [UIFont fontWithName:#"Arial" size:8.0f];
_button.layer.cornerRadius = 10.0f;
_button.layer.masksToBounds = YES;
[self.buttonView addSubview:_button];
NSLog(#"name: %#", nameString);
also on clicking button it will removed.any help would be thankful.
It works for me.Please try it.
y=20;
x=20;
for (int i=0; i<[arrAssignUsers count]; i++) {
CGRect screenRect=[[UIScreen mainScreen]bounds];
CGFloat screenWidth=screenRect.size.width;
[arrBtnStatus addObject:[NSNumber numberWithBool:NO]];
NSString *strNames=[arrAssignUsers objectAtIndex:i];
stringsize=[strNames sizeWithAttributes:
#{NSFontAttributeName: [UIFont systemFontOfSize:20.0f]}];
btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
CGFloat m=x+stringsize.width+10;
CGFloat n=screenWidth-20;
if (m<=n) {
btn.frame=CGRectMake(x, y,stringsize.width,stringsize.height);
x=x+stringsize.width +10;
}
else
{
y=y+stringsize.height+10;
x=20;
btn.frame=CGRectMake(x, y,stringsize.width,stringsize.height);
x=x+stringsize.width+10;
}
[btn setTitle:self.arrAssignUsers[i] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btn.tag=i;
[btn addTarget:self
action:#selector(notifyButtonPressedInEditTask:) forControlEvents:UIControlEventTouchUpInside];
btn.backgroundColor=WHITE_COLOR;
btn.layer.cornerRadius=10;
[btn.layer setMasksToBounds:YES];
btn.layer.borderWidth=2.0f;
btn.layer.borderColor=[UIColor orangeColor].CGColor;
[self checkNotifybtnStatus:btn];
[cell addSubview:btn];
}
}
It may helps to you.Thank you
You can use UICollectionView to create buttons. All you need to do is
1. Create custom cell with button as you want
2. When you tap on table view cell, add item to array and reload UICollectionView
3. Show buttons and it will automatically add scrollview for you.
When you tap on UICollectionView cell, remove object from array and reload UICollectionView again.
This will more easy as compared to adding buttons and setting frames.
And design UICollectionView cell in such way that it will same length as your text, use NSLayoutConstraints for it. It will work fast and smooth.
Code will be minimum and reusable.
Try out this working code...
Take UIScrollView in your Xib for buttons
//Adding menu buttons
btnArray = #[#"SYMPTOMATIC", #"SOCIAL", #"VOCATIONAL", #"PERSONAL"];
[self addButtonsInScrollMenu:btnArray];
/**
* Add Menu Buttons in Menu Scroll View
*
* #param buttonArray Array containing all menu button title
*/
#pragma mark - Add Menu Buttons in Menu Scroll View
-(void) addButtonsInScrollMenu:(NSArray *)buttonArray
{
CGFloat buttonHeight = self.menuScrollView.frame.size.height;
CGFloat cWidth = 0.0f;
for (int i = 0 ; i<buttonArray.count; i++)
{
NSString *tagTitle = [buttonArray objectAtIndex:i];
CGFloat buttonWidth = [self widthForMenuTitle:tagTitle buttonEdgeInsets:kDefaultEdgeInsets];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(cWidth, 0.0f, buttonWidth, buttonHeight);
[button setTitle:tagTitle forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:#"Roboto-Regular" size:12.0f];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self.menuScrollView addSubview:button];
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, button.frame.size.height - kButtonBorderHeight, button.frame.size.width, kButtonBorderHeight)];
bottomView.backgroundColor = [UIColor darkTextColor];
bottomView.tag = 1001;
[button addSubview:bottomView];
if (i == 0)
{
button.selected = YES;
[bottomView setHidden:NO];
}
else
{
[bottomView setHidden:YES];
}
cWidth += buttonWidth;
}
NSLog(#"scroll menu width->%f",cWidth);
self.menuScrollView.contentSize = CGSizeMake(cWidth, self.menuScrollView.frame.size.height);
}

how to make UIView work as an scrollview

I need some serious help on this problem of mine where I need to work a UIView as an ScrollView. Below uploaded picture will clear all the doubts.
I have taken four buttons along with a UIView below them along with 4 container views which I have placed one above the other so as to work along with the four buttons.. What I want now is to work UIView as an ScrollView. Whenever I click any button, the View moves forward as well as the it changes the container view. And respective container view shows whenever I click a button.
Hi better you can use UIScrollView instead of UIView like:
//Declare it
NSMutableArray * buttonArray
int selectedIndex;
-(void)setUpSegmentBar {
NSArray * namesOfMenus =#[#"Button1",#"Button2",#"Button3",#"Button4",#"Button5"];
// Scrollview added on storyBoard
myScrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 2, self.view.frame.size.width, 40)];
CGFloat scrollWidth = 0.f;
buttonArray=[[NSMutableArray alloc]init];
for ( int j=0; j<namesOfMenus.count; j++)
{
NSString * name =[namesOfMenus objectAtIndex:j];
CGSize size = [name sizeWithAttributes:
#{NSFontAttributeName: [UIFont fontWithName:font_bold size:font_size_button]}];
CGSize textSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
CGFloat strikeWidth;
if (iPAD) {
strikeWidth = self.view.frame.size.width/5.5;
}else{
strikeWidth = textSize.width;
}
CGRect frame = CGRectMake(scrollWidth, 0,strikeWidth+20, 40);
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTag:j];
button.frame = frame;
[button setBackgroundColor:[UIColor whiteColor]];
button.titleLabel.textColor=[UIColor whiteColor];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
button.layer.borderColor=[UIColor whiteColor].CGColor;
button.titleLabel.textAlignment=NSTextAlignmentCenter;
[button addTarget:self action:#selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:name forState:UIControlStateNormal];
// ScrollWidth As per Button Width
scrollWidth= scrollWidth+strikeWidth+20;
// to Check Which Button Is Selected.
if (j==selectedIndex) {
// If Selected Do UI Changes
button.backgroundColor=segment_selected_Color ;
[button setTitleColor:segment_disselected_Color forState:UIControlStateNormal];
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
[button addShaddow];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}else {
// Other Buttons
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
button.backgroundColor=segment_disselected_Color;
[button setTitleColor:segment_selected_Color forState:UIControlStateNormal];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else{
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}
// Add Buttons in Array
[buttonArray addObject:button];
// Add button on Scroll View
[myScrollView addSubview:button];
}
myScrollView.contentSize = CGSizeMake(scrollWidth, 30.f);
myScrollView.pagingEnabled = NO;
myScrollView.backgroundColor=[UIColor whiteColor];
[myScrollView setShowsHorizontalScrollIndicator:NO];
[myScrollView setShowsVerticalScrollIndicator:NO];
return myScrollView;
}
And For Handeling button action.
-(void)buttonEvent:(UIButton*)sender
{
NSInteger index= sender.tag;
selectedIndex= (int) index;
for(int i=0;i<buttonArray.count;i++)
{
UIButton * button =(UIButton*)[buttonArray objectAtIndex:i];
if (i==selectedIndex) {
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
button.backgroundColor=segment_selected_Color ;
[button setTitleColor:segment_disselected_Color forState:UIControlStateNormal];
[button addShaddow];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}else {
button.backgroundColor=segment_disselected_Color;
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
[button setTitleColor:segment_selected_Color forState:UIControlStateNormal];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else{
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}
}
CGRect frame1 = myScrollView.frame;
UIButton * bt=(UIButton*)[buttonArray objectAtIndex:index];
frame1 =bt.frame ;
// By using it button will scroll and show properly
[myScrollView scrollRectToVisible:frame1 animated:YES];
[self setupTableAfterClick];
}

Dealing with a position for a single UIButton in a custom UIAlertView

I've a nice function for customizing UIAlertView, it works perfect with 2 buttons but the issue is, how do I know there is only 1 button and not 2 buttons?
Or how do I solve the problematic positioning with only 1 button?
My code is:
- (void)layoutSubviews
{
for (id obj in self.subviews) //Search in all sub views
{
if ([obj isKindOfClass:[UIImageView class]])
{
UIImageView *imageView = (UIImageView*)obj;
float width = 284.0;
float height = 141.0;
CGSize size = CGSizeZero;
size.width = width;
size.height = height;
UIImage *newImage = [self imageWithImage:[UIImage imageNamed:#"CustomAlertView"] scaledToSize:size];
imageView.image = newImage;
[imageView sizeToFit];
}
if ([obj isKindOfClass:[UILabel class]]) // Override UILabel (Title, Text)
{
UILabel *label = (UILabel*)obj;
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.shadowColor = [UIColor clearColor];
label.font = [UIFont fontWithName:kFONT_NAME size:kFONT_SIZE];
}
if ([obj isKindOfClass:[UIButton class]]) // Override the UIButton
{
UIButton *button = (UIButton*)obj;
CGRect buttonFrame = button.frame; // Change UIButton size
buttonFrame.size = CGSizeMake(127, 35);
CGFloat newYPos = buttonFrame.origin.y + 9; // Change UIButton position
buttonFrame.origin.y = newYPos;
button.frame = buttonFrame;
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
switch (button.tag)
{
case kFIRST_BUTTON:
{
[button setBackgroundImage:[UIImage imageNamed:#"short_orange_button_off"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:#"short_orange_button_on"] forState:UIControlStateHighlighted];
}
break;
case kSECOND_BUTTON:
{
[button setBackgroundImage:[UIImage imageNamed:#"short_button_black_off"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:#"short_button_black_on"] forState:UIControlStateHighlighted];
}
break;
}
}
}
[self updateConstraints];
}
OK, just figure it out by myself, I added:
// Determine how many buttons we deal with
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
for (id obj in self.subviews)
{
if ([obj isKindOfClass:[UIButton class]])
{
self.numOfButtons++;
}
}
NSLog(#"self.numOfButtons: %d", self.numOfButtons);
});
Right after:
- (void)layoutSubviews
Then I know how many buttons I deal with.

How to make UIImage on setImage UIButton more higher

What I want is make UIButton adhere to the UIView menu when UIButton isSelected.
The black square on UINavigation is UIImage after UIButton selected.
My question is how make UIImage (black square) more higher than UIButton after selected?
this my code on UIButton Class .m:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
//...Our red stretchy
UIImage *redImage = [UIImage imageNamed:#"button_red.png"];
UIImage *redStretchy = [redImage stretchableImageWithLeftCapWidth:redImage.size.width / 2 topCapHeight:redImage.size.height / 2];
//...Initialization code
[self setFrame:frame];
[self setTitle:TITLE forState:UIControlStateNormal];
[self setBackgroundImage:redStretchy forState:UIControlStateNormal];
[[self titleLabel] setFont:[UIFont boldSystemFontOfSize:FONT_SIZE]];
[[self titleLabel] setShadowOffset:CGSizeMake(FONT_SHADOW_OFFSET, FONT_SHADOW_OFFSET)];
//...add target
[self addTarget:self action:#selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
this the target methode:
//...add target
- (void)actionButton:(id)sender {
if ([sender isSelected]) {
} else {
CGSize buttonSize = CGSizeMake(self.frame.size.width, self.frame.size.height);
[sender setImage:[self imageButton:buttonSize] forState:UIControlStateSelected];
}
if (delegate != nil && [delegate conformsToProtocol:#protocol(ButtonProtocol)]) {
if ([delegate respondsToSelector:#selector(actionButton:)]) {
[delegate performSelector:#selector(actionButton:) withObject:sender];
}
}
}
and this methode create UIIMage:
//...create image button
- (UIImage *)imageButton:(CGSize)size {
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
CGContextRef currentContex = UIGraphicsGetCurrentContext();
CGMutablePathRef path = CGPathCreateMutable();
CGRect firstRect = CGRectMake(0.0f, 0.0f, 60.f, 30.0f);
CGPathAddRect(path, NULL, firstRect);
CGContextAddPath(currentContex, path);
UIColor *fillColor = [UIColor blackColor];
CGContextSetFillColorWithColor(currentContex, fillColor.CGColor);
CGContextDrawPath(currentContex, kCGPathFill);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

UIButton font not smooth

I add some UIButton to the view, but the font in the button seems not smooth(in retina screen)....
See the image:
anyone help? Thanks!
Here is the method I adding the buttons:
- (void)setItems:(NSArray *)items {
if (_items != items) {
_items = items;
for (UIView *v in self.containerView.subviews) {
[v removeFromSuperview];
}
int i = 1;
CGFloat y = 8;
for (id item in _items) {
UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeCustom];
itemButton.frame = CGRectMake(0, y, self.containerView.bounds.size.width, 35);
itemButton.tag = i;
[itemButton setTitle:item forState:UIControlStateNormal];
[itemButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[itemButton setBackgroundImage:[UIImage imageNamed:#"bg.png"] forState:UIControlStateHighlighted];
itemButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
[itemButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
y += 35;
[self.containerView addSubview:itemButton];
i++;
}
}
}
The problem resolved:
self.containerView = [[UIScrollView alloc] initWithFrame:frame];
UIScreen *mainScreen = [UIScreen mainScreen];
if ([mainScreen respondsToSelector:#selector(scale)]) {
self.containerView.contentScaleFactor = mainScreen.scale;
}
self.containerView.contentScaleFactor = mainScreen.scale;

Resources