UIScrollView subview not always clickable - objective-c

I'm adding subviews to an UIScrollView. For this question I'm simplifying the added view : testView it contains an UIButton
My Scroll View is working great, but the touch on the buttons is not working well.
I can click on the first button but only on the (approximative) 100 first pixels.
the scrolling is working very well.
I cannot click on the end of the first button
I cannot click on the other buttons
here is my code :
__block CGFloat scrollViewContentSize = 0;
__block CGFloat buttonRectOrigineY = 0;
[self.itemsToDisplay enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
CGRect frameTest = CGRectMake(0, buttonRectOrigineY/2, 320, 200);
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
testButton.frame = frameTest;
UIView *testView = [[UIView alloc] initWithFrame:frameTest];
[testView addSubview:testButton];
[self.articleScrollView addSubview:testView];
buttonRectOrigineY += 200;
scrollViewContentSize += 200;
}];
[self.articleScrollView setContentSize:CGSizeMake(320, scrollViewContentSize)];
here is image to understand well my problem :

You can use bringSubviewToFront to avoid the issue
CGRect frameTest = CGRectMake(0, buttonRectOrigineY/2, 320, 200);
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
testButton.frame = frameTest;
UIView *testView = [[UIView alloc] initWithFrame:frameTest];
[testView addSubview:testButton];
[testView bringSubviewToFront:testButton];
[self.articleScrollView addSubview:testView];
[self.articleScrollView bringSubviewToFront:testView];
If you have issues again, apply boarder around the button and check it the button area that visible manually.

I was mistaking the frame of my button and view. Here a working code if it can help anyone.
__block CGFloat scrollViewContentSize = 0;
__block CGFloat buttonRectOrigineY = 0;
[self.itemsToDisplay enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
CGRect frameTestButton = CGRectMake(0, 0, 300, 150);
CGRect frameTestView = CGRectMake(10, buttonRectOrigineY, 300, 200);
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
testButton.frame = frameTestButton;
testButton.backgroundColor = [UIColor greenColor];
UIView *testView = [[UIView alloc] initWithFrame:frameTestView];
if(idx == 0)
testView.backgroundColor = [UIColor yellowColor];
if(idx == 1)
testView.backgroundColor = [UIColor orangeColor];
if(idx == 2)
testView.backgroundColor = [UIColor redColor];
if(idx == 3)
testView.backgroundColor = [UIColor magentaColor];
if(idx == 4)
testView.backgroundColor = [UIColor purpleColor];
if(idx <= 4){
LogDebug(#"idx : %lu", (unsigned long)idx);
[testView addSubview:testButton];
[self.articleScrollView addSubview:testView];
[self.articleScrollView bringSubviewToFront:testView];
buttonRectOrigineY += 200;
scrollViewContentSize += 200;
}
}];
[self.articleScrollView setContentSize:CGSizeMake(320, scrollViewContentSize)];

Related

UIButton is not setting text

I seem to have a problem in my Objective C iOS app where I am creating multiple buttons depending on the amount of objects in an array. I know Swift, so I replicated the logic into Swift, and it worked. Yet in Objective C, I am unable to see the text of the button (after I remove the for loop) or create multiple buttons. For example, I have an array full of three names. I would like to create a button for each name with the title set to the corresponding name. So far, I have this:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *ages = [[NSMutableArray alloc] init];
for (int i = 0; i > 10; i++) {
[ages addObject:[NSString stringWithFormat:#"%i", i]];
}
UIScrollView *scrollView= [[UIScrollView alloc]initWithFrame:self.view.frame];
scrollView.delegate= self;
self.automaticallyAdjustsScrollViewInsets= NO;
scrollView.backgroundColor= [UIColor clearColor];
scrollView.scrollEnabled= YES;
scrollView.userInteractionEnabled= YES;
[scrollView setShowsHorizontalScrollIndicator:NO];
[scrollView setShowsVerticalScrollIndicator:NO];
CGFloat xValue = 0;
for(int x=0; x > ages.count; x++){
UIButton *button= [[UIButton alloc] initWithFrame:CGRectMake(xValue ,0 , 172 ,65)];
UIColor *buttonOutline = [[UIColor redColor] CGColor];
button.layer.borderColor = [buttonOutline CGColor];
button.layer.backgroundColor = [[UIColor clearColor] CGColor];
button.layer.borderWidth = 1.0;
button.layer.cornerRadius = 6.0;
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:13.0]];
button.titleLabel.text = [ages objectAtIndex:x];
[button addTarget:self action:#selector(test:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
NSLog(#"Button Added");
xValue = button.frame.size.width + 40;
}
scrollView.contentSize = CGSizeMake(xValue, 65);
[self.view addSubview:scrollView];
}
- (void)test:(UIButton*)sender{
NSLog(#"Clicked %#", sender.titleLabel.text);
}
#end
If anyone sees anything wrong with this code, please point it out!
Thanks,
Arnav K.
I found four problems (there may be others) that stop this working correctly:
1) The for loop bound when setting up the ages array is incorrect.
2) The for loop bound when creating the buttons is incorrect.
3) You are setting the buttonOutline colour incorrectly.
4) xValue is being updated incorrectly.
Here is the viewDidLoad method after the changes have been made:
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *ages = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) { // UPDATED
[ages addObject:[NSString stringWithFormat:#"%i", i]];
}
UIScrollView *scrollView= [[UIScrollView alloc]initWithFrame:self.view.frame];
scrollView.delegate= self;
self.automaticallyAdjustsScrollViewInsets= NO;
scrollView.backgroundColor= [UIColor clearColor];
scrollView.scrollEnabled= YES;
scrollView.userInteractionEnabled= YES;
[scrollView setShowsHorizontalScrollIndicator:NO];
[scrollView setShowsVerticalScrollIndicator:NO];
CGFloat xValue = 0;
for(int x=0; x < ages.count; x++){ // UPDATED
UIButton *button= [[UIButton alloc] initWithFrame:CGRectMake(xValue ,0 , 172 ,65)];
UIColor *buttonOutline = [UIColor redColor]; // UPDATED
button.layer.borderColor = [buttonOutline CGColor];
button.layer.backgroundColor = [[UIColor clearColor] CGColor];
button.layer.borderWidth = 1.0;
button.layer.cornerRadius = 6.0;
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:13.0]];
button.titleLabel.text = [ages objectAtIndex:x];
[button addTarget:self action:#selector(test:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
NSLog(#"Button Added");
xValue += button.frame.size.width + 40; // UPDATED
}
scrollView.contentSize = CGSizeMake(xValue, 65);
[self.view addSubview:scrollView];
}
I have marked the four lines I changed with a UPDATED comment so you can compare them to the original.
EDIT
To change the text and text colour use the following:
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button setTitle:[ages objectAtIndex:x] forState:UIControlStateNormal];
and remove this:
button.titleLabel.text = [ages objectAtIndex:x];
You need to do this because you can set different text for the different states of the button and this is all handled automatically for you.

How do I change a button's color when pressed and reset to original color when a different button are pressed?

I have created buttons dynamically based on array count ,if i pressed it will move to next page .i want to change the background color of the button if it is pressed .i pressed 1st button its background color should changed ,and den if i pressed anyother buttons the first pressed button should get into default color of the button , and the new pressed button's background color should changed ,
please help me to do this ,On button clicked method i have tried like this ,
- (IBAction)btn1Tapped:(id)sender {
UIButton *btn = (UIButton *) sender;
selected = YES;
if (selected) {
[btn setBackgroundColor:[UIColor redColor]];
}
}
and this my button creation code ,
int buttonheight = 30;
int horizontalPadding = 20;
int verticalPadding = 20;
int totalwidth = self.view.frame.size.width;
int x = 10;
int y = 150;
for (int i=0; i<array.count; i++)
{
NSString* titre = [array objectAtIndex:i];
CGSize contstrainedSize = CGSizeMake(200, 40);//The maximum width and height
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:20.0], NSFontAttributeName,
nil];
CGRect frame = [titre boundingRectWithSize:contstrainedSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDictionary context:nil];
int xpos = x + CGRectGetWidth(frame);
if (xpos > totalwidth) {
y =y +buttonheight+ verticalPadding;
x = 10;
}
UIButton *word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.word = word;
NSLog(#"%#", NSStringFromCGRect(frame));
word = [UIButton buttonWithType:UIButtonTypeRoundedRect];
word.frame = CGRectMake(x, y, CGRectGetWidth(frame)+5, CGRectGetHeight(frame));
[word setTitle:titre forState:UIControlStateNormal];
[word setTitle:titre forState:UIControlStateSelected];
word.backgroundColor = [UIColor colorWithRed:30.0/255.0 green:134.0/255.0 blue:255.0/255.0 alpha:1.0];
[word setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[word setTag:i];
[word addTarget:self action:#selector(btn1Tapped:) forControlEvents:UIControlEventTouchUpInside];
word.layer.borderColor = [UIColor blackColor].CGColor;
word.layer.borderWidth = 1.0f;
word.layer.cornerRadius = 5;
[self.view addSubview:word];
x =x+horizontalPadding+CGRectGetWidth(frame);
}
- (IBAction)allBtnSharedTappedevent:(id)sender {
UIButton *btn = (UIButton *) sender;
[btn setBackgroundColor:[UIColor redColor]];
//loop through all your buttons
for(UIView *view in [self.view subviews]){
if([view isKindOfClass:[UIButton class]]){
if(view != btn){
UIButton* btn1 = (UIButton*) view;
[btn1 setBackgroundColor:[UIColor grayColor]];
}
}
}
}
Keep the buttons in an array.
#property (nonatomic, copy, readonly) NSArray<UIButton *> *buttons;
Then in your method that handles the tap, do something like this.
- (IBAction)buttonTapped:(UIButton *)sender {
// Loop through all buttons, clearing the background color
for (UIButton *button in self.buttons) {
button.backgroundColor = [UIColor clearColor];
}
// Set the background color for the selected button
sender.backgroundColor = [UIColor redColor];
}
You should avoid using the tag property of UIView, it will just cause you headaches down the road.
give your button tag number like 1,2,3,4 ... etc
then
- (IBAction)btn1Tapped:(id)sender {
UIButton *btn = (UIButton *) sender;
[btn setBackgroundColor:[UIColor redColor]];
loop through all your buttons
for(int i = 1;i <= total numbers of button; i++){
if(btn.tag != i){
UIButton* btn1 = [myView viewWithTag:i];
[btn1 setBackgroundColor:[UIColor graycolor]];
}
}
}

Horizontal UIScrollView with multiple textfields to display

I'm new to Xcode. I want to make a UIScrollView with multiple pages and each page having multiple UITextFields which vary on each page. I made UIScrollView with paging enabled. Now I'm stuck at displaying textfield's on scroll pages.
Here is my code so far:
//set the paging to yes
self.scrollview.pagingEnabled = YES;
// create 5 pages
NSUInteger numberOfViews = 5;
for (int i = 0; i < numberOfViews; i++)
{
//set the origin of the sub view
CGFloat myOrigin = i * self.view.frame.size.width;
//create the sub view and allocate memory
myView = [[UIView alloc] initWithFrame:CGRectMake(myOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
//create a label and add to the sub view
CGRect myFrame = CGRectMake(10.0f, 10.0f, 200.0f, 25.0f);
textLabel = [[UILabel alloc] initWithFrame:myFrame];
textLabel.font = [UIFont boldSystemFontOfSize:16.0f];
textLabel.textAlignment = NSTextAlignmentLeft;
[myView addSubview:textLabel];
//create a text field and add to the sub view
myFrame.origin.y += myFrame.size.height + 10.0f;
textField = [[UITextField alloc] initWithFrame:myFrame];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.tag = i+1;
[myView addSubview:textField];
//set the background to different color
//set the scroll view delegate to self so that we can listen for changes
self.scrollview.delegate = self;
//add the subview to the scroll view
[self.scrollview addSubview:myView];
}
//scroll horizontally
self.scrollview.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews,
self.scrollview.frame.size.height);
//we set the origin to the 1rd page
CGPoint scrollPoint = CGPointMake(self.view.frame.size.width * 0, 0);
//change the scroll view offset the the 1rd page so it will start from there
[scrollview setContentOffset:scrollPoint animated:YES];
[self.view addSubview:self.scrollview];
}
Use This code here textfieldCount is
for (int j=0; j < textFieldCount; j++)
{
myFrame.origin.y += myFrame.size.height + 10.0f*(j+1);
UITextField *textField = [[UITextField alloc] initWithFrame:myFrame];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.tag = j+1;
[myView addSubview:textField];
}
Hope you got your answer.

Create Grid of UIVews in NSArray

What I am trying to do is align views in a grid that are in an array. I have created the views and the array.
for (int i = 0; i < [directoryContents count]; i++){
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,120)];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 100, 100);
button.accessibilityIdentifier = [directoryContents objectAtIndex:i];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 100, 20)];
label.textAlignment = NSTextAlignmentCenter;
label.text = [directoryContents objectAtIndex:i];
[containerView addSubview:button];
[containerView addSubview:label];
[self.view addSubview:containerView];
[_containerViewArray addObject:containerView];
}
[self layoutViews:_containerViewArray inView:self.view];
What I have working is aligning them next to each other the problem I am having is I need to have them wrap down instead of going off the edge. What I am doing to algin them is this
- (void)layoutViews:(NSArray *)views inView:(UIView *)contentView
{
NSInteger overallWidth = 0;
for ( UIView *view in views ) {
overallWidth += view.frame.size.width;
}
CGSize contentSize = contentView.frame.size;
CGFloat startOffset = (contentSize.height - overallWidth)/2.0;
CGFloat offset = startOffset;
for ( UIView *view in views ) {
CGRect frame = view.frame;
frame.origin.x = offset;
view.frame = frame;
offset += view.frame.size.width;
}
}
If we assumed that we have an array of sections (your views) and you need to layout 3 item per row the view has size 98*98 and spacing 6.5px horizontally and 8px Vertically
for (int i = 0; i< [sectionsArray count]; i++) {
int row = (int)i/3;
int col = i%3;
float x = 6.5 + (104.5*col);
float y = 8 + (106*row);
UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(x, y, 98, 98)];
sectionView.backgroundColor = [UIColor clearColor];
//button
UIButton *sectionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[sectionButton setTintColor:[UIColor grayColor]];
sectionButton.frame = CGRectMake(0, 0, 98, 98);
sectionButton.tag = i+100;
[sectionButton addTarget:self action:#selector(showSectionDetail:) forControlEvents:UIControlEventTouchUpInside];
[sectionView addSubview:sectionButton];
//adding title
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 75, 98, 20)];
titleLabel.textAlignment = UITextAlignmentCenter;
titleLabel.backgroundColor=[UIColor clearColor];
titleLabel.font=[UIFont fontWithName:#"Helvetica" size:14];
titleLabel.textColor = [UIColor colorWithRed:241.0/255.0 green:124.0/255.0 blue:22.0/255.0 alpha:1.0];
titleLabel.text = [[sectionsArray objectAtIndex:i] objectForKey:#"Title"];
[sectionView addSubview:titleLabel];
[titleLabel release];
[scroll addSubview:sectionView];
[sectionView release];
}
int numberOfRows;
if ([sectionsArray count]/3.0f == 0) {
numberOfRows = [sectionsArray count]/3;
}else{
numberOfRows = [sectionsArray count]/3 +1;
}
scroll setContentSize:CGSizeMake(320, numberOfRows*106);
Here's what I used until the UICollectionView was released, easy to modify to accommodate for how many rows you want in the grid, and the size of the views.
NSUInteger buttonWidth = 100;
NSUInteger buttonHeight = 100;
NSUInteger space = 5;
float scrollContentY = (ceilf((float)imageNames.count / 3.0f) * (buttonHeight + space));
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
int row = idx / 3;
int column = idx % 3;
UIView *view = [UIView new];
[view setBackgroundColor:[UIColor redColor]];
view.frame = CGRectMake((buttonWidth + space) * column + space, (buttonHeight + space) * row + space , buttonWidth, buttonHeight);
[view setTag:(NSInteger)idx];
[self.scrollView addSubview:view];
[self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width, scrollContentY)];
}];
Mind you, this might not be advisable if you have a large array to enumerate because this doesn't have any kind of reusable views. It will alloc/init a view for every item in the array.

UIScrollView and UIPageControl, what am I doing wrong?

I have a class which is predefining some labels and binding their values in a UIScrollView.
I've managed to show those labels, but now I'm stuck at putting a label at the 2nd part of the ScrollView.
I've pushed my project to gitHub.
I can change the label's place on the already visible part, but I must be overlooking something.
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = _detail.name;
UIColor *bgColor = [UIColor blackColor];
UIColor *txtColor = [UIColor grayColor];
CGRect frame;
frame.origin.x = 0;
frame.origin.y = 0;
frame.size.width = _scrollView.frame.size.width *2;
NSString *phoneNr = (_detail.phoneNr == nil) ? #"Not specified" : _detail.phoneNr;
_telLabel = [self prepareLabel:phoneNr textColor:txtColor bgColor:bgColor page:0 y:telNrYAxis];
_webLabel = [self prepareLabel:#"Visit website" textColor:txtColor bgColor:bgColor page:0 y:websiteYAxis];
_detail.address = [_detail.address stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"\n\t "]];
NSArray *addressArrComponents = [_detail.address componentsSeparatedByString:#","] ;
_addressLabel = [self prepareLabel:[addressArrComponents componentsJoinedByString:#"\n"] textColor:txtColor bgColor:bgColor page:0 y:addressYAxis];
UILabel *lbl = [self prepareLabel:#"Derp" textColor:txtColor bgColor:bgColor page:1 y:0];
_detailView = [[UIView alloc] initWithFrame:frame];
_detailView.backgroundColor = [UIColor blackColor];
[_detailView addSubview:_webLabel];
[_detailView addSubview:_addressLabel];
[_detailView addSubview:_telLabel];
[_detailView addSubview:lbl];
[_scrollView addSubview:_detailView];
NSLog(#"%f",self.view.frame.size.height - (_scrollView.frame.origin.y + _scrollView.frame.size.height) );
_pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height - 250 , self.view.frame.size.width/4, 120)];
_pageControl.numberOfPages=2;
_pageControl.currentPage=0;
[_pageControl addTarget:self action:#selector(pageChange:) forControlEvents:UIControlEventTouchDown];
_scrollView.contentSize = CGSizeMake(800,800);
_scrollView.delegate=self;
_scrollView.backgroundColor = [UIColor blackColor];
_scrollView.pagingEnabled=YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
[self pageChange:0];
[self.view addSubview:_pageControl];
// Do any additional setup after loading the view.
}
-(UILabel*)prepareLabel:(NSString*) text textColor:(UIColor*)textColor bgColor:(UIColor*)backgroundColor page:(int)page y:(int) yPos{
int lines = [[text componentsSeparatedByString:#"\n"] count];
CGRect labelFrame = CGRectMake(_detailView.frame.size.width * page +20,yPos,self.view.frame.size.width, [UIFont systemFontSize]*lines);
UILabel *returnLabel = [[UILabel alloc] initWithFrame:labelFrame];
returnLabel.text = text;
returnLabel.backgroundColor = backgroundColor;
returnLabel.textColor = textColor;
[returnLabel setNumberOfLines:lines];
[returnLabel sizeToFit];
return returnLabel;
}
- (void)loadScrollViewWithPage:(int)page {
NSLog(#"Derped");
}
-(IBAction)pageChange:(id)sender{
int page=_pageControl.currentPage;
CGRect frame = _scrollView.frame;
frame.origin.x = _scrollView.frame.size.width * page;
frame.origin.y = 0;
//CGRect frame= (page == 0) ? _detailFrame : _reviewFrame;
NSLog(#"%f",frame.origin.x);
[_scrollView scrollRectToVisible:frame animated:YES];
}
The delegate -(IBAction)pageChange:(id)sender gets fired, but I must be doing something wrong with the frames somewhere :s
Please take a look!
Try to implement this method may help you :
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat pageWidth = self.scrollView.frame.size.width;
float fractionalPage = self.scrollView.contentOffset.x / pageWidth;
NSInteger page = lround(fractionalPage);
self.pageControl.currentPage = page;
}