I have created an UITableView in my app programatically. I have a strange problem. I have never seen this and I think everything is alright. It seems like all the table goes down and I only can see the first row. I want to create the same UITableView grouped as the settings tableViews in iOS7
But the Image in iOS 6 it is strange too.. I have written a NSLog and the height is 132 = 3 items * 44 height cell.
Here it is the code.
static float x = 10.0;
static float y = 80.0;
static NSString *CategoryCellIdentifier = #"CategoryCell";
static float kHeightCell = 44.0;
#interface LKLHomeViewController ()
#property (nonatomic, strong) NSArray *itemsArray;
#property (nonatomic, strong) UITableView *categoryTableView;
#end
#implementation LKLHomeViewController
#synthesize itemsArray;
#synthesize categoryTableView;
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor grayColor]];
// Adding tableView to self.view
[self.view addSubview:self.categoryTableView];
}
#pragma mark - Custom getter
-(NSArray *)itemsArray
{
if(!itemsArray){
itemsArray = #[#"Near", #"Kind of" , #"More.."];
return itemsArray;
}
return itemsArray;
}
- (UITableView *)categoryTableView
{
//custom init of the tableview
if (!categoryTableView) {
CGFloat height = kHeightCell * [self.itemsArray count];
CGFloat width = self.view.frame.size.width - (x*2);
CGRect tableFrame = CGRectMake(x, y, width, height);
// regular table view
categoryTableView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStyleGrouped];
categoryTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
categoryTableView.delegate = self;
categoryTableView.dataSource = self;
categoryTableView.backgroundColor = [UIColor whiteColor];
[categoryTableView setScrollEnabled:NO];
[[categoryTableView layer] setCornerRadius:5.0f];
return categoryTableView;
}
return categoryTableView;
}
Related
Our iPhone app currently supports IOS 8/9/10. I am having difficulty supporting voice over accessibility for a custom UITableViewCell. I have gone through the following SO posts, but none of the suggestions have worked. I want individual components to be accessible.
Custom UITableview cell accessibility not working correctly
Custom UITableViewCell trouble with UIAccessibility elements
Accessibility in custom drawn UITableViewCell
https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/iPhoneAccessibility/Making_Application_Accessible/Making_Application_Accessible.html#//apple_ref/doc/uid/TP40008785-CH102-SW10
http://useyourloaf.com/blog/voiceover-accessibility/
Unfortunately for me, the cell is not detected by the accessibility inspector. Is there a way to voice over accessibility to pick up individual elements within the table view cell? When debugging this issue on both device and a simulator, I found that the XCode calls isAccessibleElement function. When the function returns NO, then the rest of the methods are skipped. I am testing on IOS 9.3 in XCode.
My custom table view cell consists of a label and a switch as shown below.
The label is added to the content view, while the switch is added to a custom accessory view.
The interface definition is given below
#interface MyCustomTableViewCell : UITableViewCell
///Designated initializer
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier;
///Property that determines if the switch displayed in the cell is ON or OFF.
#property (nonatomic, assign) BOOL switchIsOn;
///The label to be displayed for the alert
#property (nonatomic, strong) UILabel *alertLabel;
#property (nonatomic, strong) UISwitch *switch;
#pragma mark - Accessibility
// Used for setting up accessibility values. This is used to generate accessibility labels of
// individual elements.
#property (nonatomic, strong) NSString* accessibilityPrefix;
-(void)setAlertHTMLText:(NSString*)title;
#end
The implementation block is given below
#interface MyCustomTableViewCell()
#property (nonatomic, strong) UIView *customAccessoryView;
#property (nonatomic, strong) NSString *alertTextString;
#property (nonatomic, strong) NSMutableArray* accessibleElements;
#end
#implementation MyCustomTableViewCell
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
if(self = [super initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:reuseIdentifier]) {
[self configureTableCell];
}
return self;
}
- (void)configureTableCell
{
if (!_accessibleElements) {
_accessibleElements = [[NSMutableArray alloc] init];
}
//Alert label
self.alertLabel = [[self class] makeAlertLabel];
[self.contentView setIsAccessibilityElement:YES];
//
[self.contentView addSubview:self.alertLabel];
// Custom AccessoryView for easy styling.
self.customAccessoryView = [[UIView alloc] initWithFrame:CGRectZero];
[self.customAccessoryView setIsAccessibilityElement:YES];
[self.contentView addSubview:self.customAccessoryView];
//switch
self.switch = [[BAUISwitch alloc] initWithFrame:CGRectZero];
[self.switch addTarget:self action:#selector(switchWasFlipped:) forControlEvents:UIControlEventValueChanged];
[self.switch setIsAccessibilityElement:YES];
[self.switch setAccessibilityTraits:UIAccessibilityTraitButton];
[self.switch setAccessibilityLabel:#""];
[self.switch setAccessibilityHint:#""];
self.switch.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self.customAccessoryView addSubview:self.switch];
}
+ (UILabel *)makeAlertLabel
{
UILabel *alertLabel = [[UILabel alloc] initWithFrame:CGRectZero];
alertLabel.backgroundColor = [UIColor clearColor];
alertLabel.HTMLText = #"";
alertLabel.numberOfLines = 0;
alertLabel.lineBreakMode = LINE_BREAK_WORD_WRAP
[alertLabel setIsAccessibilityElement:YES];
return alertLabel;
}
-(void)setAlertHTMLText:(NSString*)title{
_alertTextString = [NSString stringWithString:title];
[self.alertLabel setText:_alertTextString];
}
- (BOOL)isAccessibilityElement {
return NO;
}
// The view encapsulates the following elements for the purposes of
// accessibility.
-(NSArray*) accessibleElements {
if (_accessibleElements && [_accessibleElements count] > 0) {
[_accessibleElements removeAllObjects];
}
// Fetch a new copy as the values may have changed.
_accessibleElements = [[NSMutableArray alloc] init];
UIAccessibilityElement* alertLabelElement =
[[UIAccessibilityElement alloc] initWithAccessibilityContainer:self];
//alertLabelElement.accessibilityFrame = [self convertRect:self.contentView.frame toView:nil];
alertLabelElement.accessibilityLabel = _alertTextString;
alertLabelElement.accessibilityTraits = UIAccessibilityTraitStaticText;
[_accessibleElements addObject:alertLabelElement];
UIAccessibilityElement* switchElement =
[[UIAccessibilityElement alloc] initWithAccessibilityContainer:self];
// switchElement.accessibilityFrame = [self convertRect:self.customAccessoryView.frame toView:nil];
switchElement.accessibilityTraits = UIAccessibilityTraitButton;
// If you want custom values, just override it in the invoking function.
NSMutableString* accessibilityString =
[NSMutableString stringWithString:self.accessibilityPrefix];
[accessibilityString appendString:#" Switch "];
if (self.switchh.isOn) {
[accessibilityString appendString:#"On"];
} else {
[accessibilityString appendString:#"Off"];
}
switchElement.accessibilityLabel = [accessibilityString copy];
[_accessibleElements addObject:switchElement];
}
return _accessibleElements;
}
// In case accessibleElements is not initialized.
- (void) initializeAccessibleElements {
_accessibleElements = [self accessibleElements];
}
- (NSInteger)accessibilityElementCount
{
return [_accessibleElements count]
}
- (id)accessibilityElementAtIndex:(NSInteger)index
{
[self initializeAccessibleElements];
return [_accessibleElements objectAtIndex:index];
}
- (NSInteger)indexOfAccessibilityElement:(id)element
{
[self initializeAccessibleElements];
return [_accessibleElements indexOfObject:element];
}
#end
First of all, from the pattern you described, I'm not sure why you would want to differentiate between different elements in a cell. Generally, Apple keeps every cell a single accessibility element. A great place to see the expected iOS VO behavior for cells with labels and switches is in Settings App.
If you still believe the best way to handle your cells is to make them contain individual elements, then that is actually the default behavior of a cell when the UITableViewCell itself does not have an accessibility label. So, I've modified your code below and run it on my iOS device (running 9.3) and it works as you described you would like.
You'll notice a few things.
I deleted all the custom accessibilityElements code. It is not necessary.
I deleted the override of isAccessibilityElement on the UITableViewCell subclass itself. We want default behavior.
I commented out setting the content view as an accessibilityElement -- we want that to be NO so that the tree-builder looks inside of it for elements.
I set customAccessoryView's isAccessibilityElement to NO as well for the same reason as above. Generally, NO says "keep looking down the tree" and YES says "stop here, this is my leaf as far as accessibility is concerned."
I hope this is helpful. Once again, I do really encourage you to mimic Apple's VO patterns when designing for Accessibility. I think it's awesome that you're making sure your app is accessible!
#import "MyCustomTableViewCell.h"
#interface MyCustomTableViewCell()
#property (nonatomic, strong) UIView *customAccessoryView;
#property (nonatomic, strong) NSString *alertTextString;
#property (nonatomic, strong) NSMutableArray* accessibleElements;
#end
#implementation MyCustomTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if(self = [super initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:reuseIdentifier]) {
[self configureTableCell];
}
return self;
}
// just added this here to get the cell to lay out for myself
- (void)layoutSubviews {
[super layoutSubviews];
const CGFloat margin = 8;
CGRect b = self.bounds;
CGSize labelSize = [self.alertLabel sizeThatFits:b.size];
CGFloat maxX = CGRectGetMaxX(b);
self.alertLabel.frame = CGRectMake(margin, margin, labelSize.width, labelSize.height);
CGSize switchSize = [self.mySwitch sizeThatFits:b.size];
self.customAccessoryView.frame = CGRectMake(maxX - switchSize.width - margin * 2, b.origin.y + margin, switchSize.width + margin * 2, switchSize.height);
self.mySwitch.frame = CGRectMake(margin, 0, switchSize.width, switchSize.height);
}
- (void)configureTableCell
{
//Alert label
self.alertLabel = [[self class] makeAlertLabel];
//[self.contentView setIsAccessibilityElement:YES];
//
[self.contentView addSubview:self.alertLabel];
// Custom AccessoryView for easy styling.
self.customAccessoryView = [[UIView alloc] initWithFrame:CGRectZero];
[self.customAccessoryView setIsAccessibilityElement:NO]; // Setting this to NO tells the the hierarchy builder to look inside
[self.contentView addSubview:self.customAccessoryView];
self.customAccessoryView.backgroundColor = [UIColor purpleColor];
//switch
self.mySwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
//[self.mySwitch addTarget:self action:#selector(switchWasFlipped:) forControlEvents:UIControlEventValueChanged];
[self.mySwitch setIsAccessibilityElement:YES]; // This is default behavior
[self.mySwitch setAccessibilityTraits:UIAccessibilityTraitButton]; // No tsure why this is here
[self.mySwitch setAccessibilityLabel:#"my swich"];
[self.mySwitch setAccessibilityHint:#"Tap to do something."];
self.mySwitch.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self.customAccessoryView addSubview:self.mySwitch];
}
+ (UILabel *)makeAlertLabel
{
UILabel *alertLabel = [[UILabel alloc] initWithFrame:CGRectZero];
alertLabel.backgroundColor = [UIColor clearColor];
alertLabel.text = #"";
alertLabel.numberOfLines = 0;
[alertLabel setIsAccessibilityElement:YES];
return alertLabel;
}
-(void)setAlertHTMLText:(NSString*)title{
_alertTextString = [NSString stringWithString:title];
[self.alertLabel setText:_alertTextString];
}
#end
I have a UIView that I am using as a simple onboarding view. I simply shows n images, that the user can swipe through.
The only image that loads is the very first image "OnBoard-1". The other images are there when I debug the what is being added to the image view.
What am I doing wrong?
.h
#import <UIKit/UIKit.h>
#interface OnBoardingView : UIView
- (void)setImages:(NSArray *)newImages;
#end
Here is the .m file
#import "OnBoardingView.h"
#interface OnBoardingView () <UIScrollViewDelegate>
{
UIPageControl *pageControl;
NSArray *contentImages;
}
#property (nonatomic, retain) UIPageControl *pageControl;
#property (nonatomic, retain) NSArray *contentImages;
#end
#implementation OnBoardingView
#synthesize pageControl;
#synthesize contentImages;
- (id) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) { }
return self;
}
#pragma mark - Override contentImages setter
- (void)setImages:(NSArray *)newImages {
if (newImages != self.contentImages) {
self.contentImages = newImages;
[self setup];
}
}
#pragma mark - Carousel setup
- (void)setup {
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.frame];
[scrollView setDelegate:self];
[scrollView setShowsHorizontalScrollIndicator:NO];
[scrollView setPagingEnabled:YES];
[scrollView setBounces:NO];
CGSize scrollViewSize = scrollView.frame.size;
for (NSInteger i = 0; i < [self.contentImages count]; i++) {
CGRect slideRect = CGRectMake(scrollViewSize.width * i, 0, scrollViewSize.width, scrollViewSize.height);
UIView *slide = [[UIView alloc] initWithFrame:slideRect];
[slide setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0]];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.frame];
[imageView setImage:[UIImage imageNamed:[self.contentImages objectAtIndex:i]]];
NSLog(#"Image named: %#", [self.contentImages objectAtIndex:i]);
[slide addSubview:imageView];
[scrollView addSubview:slide];
}
UIPageControl *tempPageControll = [[UIPageControl alloc] initWithFrame:CGRectMake(0, scrollViewSize.height - 20, scrollViewSize.width, 20)];
[self setPageControl:tempPageControll];
[self.pageControl setNumberOfPages:[self.contentImages count]];
[scrollView setContentSize:CGSizeMake(scrollViewSize.width * [self.contentImages count], scrollViewSize.height)];
[self addSubview:scrollView];
[self addSubview:self.pageControl];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
[self.pageControl setCurrentPage:page];
}
#end
You initialise the imageView with the frame of the scrollView, that's in any case not right and may be the cause of your problem.
BTW:
Your property handling looks a bit strange (why the synthesizing instead of just using a normal property only?), and why do you compare the arrays by pointer (newImages != self.contentImages)?
If you want to show the images in paging directly you can assign the number of pages count.And apply the swipe gesture(left and right) to imageview.And based on left and right swipe,you can change the image of imageview.
I am trying to create a grid of UIButtons . The row and column values are dynamic.I know how to create a grid .However making it using dynamic values is the problem.
-(void)makeLayoutWithMinRow:(int)minRow maxRow:(int)maxRow minColumn:(int)minColumn maxColumn:(int)maxColumn {
NSInteger intLeftMargin = 10; // horizontal offset from the edge of the screen
NSInteger intTopMargin = 10; // vertical offset from the edge of the screen
NSInteger intYSpacing = 30; // number of pixels between the button origins (vertically)
NSInteger intXTile;
NSInteger intYTile;
NSInteger width;
width = ((self.layoutView.frame.size.width-(maxColumn * 5))/maxColumn);
for (int y = minRow; y < maxRow; y++)
{
for (int x = minColumn; x < maxColumn; x++)
{
intXTile = (x * width) + intLeftMargin;
intYTile = (y * intYSpacing) + intTopMargin;
UIButton *buttons[x][y] = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
//Here I get error : Variable-sized object may not be initialised.
[self.layoutView addSubview:buttons[x][y]];
}
}
}
I did try the option as suggested by Cornelius below to store the button in array.
sButton = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
[buttons addObject:sButton];
How to add these buttons to view in this case?
for (UIButton *obj in buttons) {
[self.layoutView addSubview:obj]; //Doesn't work
}
Here is the one which replaces UICollectionView.I have tried
PSTCollectionView and it gives you the expected results. Try this.
You can use PSTCollectionView.
Use UICollectionView to create such grid.
Here is a tutorial. For your case, it's UIButton instead of UIImageView in this tutorial.
It seems all you're trying to achieve here is a lookup for the buttons later.
So you will need a variable (or property) on your instance to hold the references, not just a local variable during creation.
There are many ways of solving your problem, one simple yet efficient way to store the references is a 'NSMutableDictionary'.
Declare a property in your class:
#property (nonatomic, strong) NSMutableDictionary *buttonDictionary;
Set it up in your loop:
_buttonDictionary = [[NSMutableDictionary alloc] init];
In your loop, encode the x/y position, for example using an NSIndexPath, abusing row/section:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:y inSection:x];
Create button and add to your dictionary and superview:
UIButton *freshButton = [UIButton buttonWithType:...]; // Much better than initWithFrame
freshButton.frame = ...;
_buttonDictionary[indexPath] = freshButton;
[self.layoutView addSubview:freshButton];
If you want to look up a button later by x/y indices, just do
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:y inSection:x];
UIButton *requestedButton = _dictionary[indexPath];
Please note that I'm using the [] syntax on dictionaries here - you may use the classic methods objectForKey: and setObject:forKey: instead.
You can use UICollectionView and set the dynamic values as you desired or customized as per your requirement. This is very easy and effective way to develop grid view. Here I explained a simple code for grid view:
Like this :
#interface DashboardViewController : AbstractController <UICollectionViewDataSource, UICollectionViewDelegate>{
NSMutableArray *dataSource;
}
#property (nonatomic, strong) UICollectionView *dashboardCollectionView;
#property (nonatomic, strong) ModulesDataModel *modulesDataModel;
#end
/*****************.m********************/
- (void)viewDidLoad {
[super viewDidLoad];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
_dashboardCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 135, 1024, 537) collectionViewLayout:layout];
[_dashboardCollectionView setDataSource:self];
[_dashboardCollectionView setDelegate:self];
[_dashboardCollectionView registerClass:[CellMaster class] forCellWithReuseIdentifier:#"Reuse"];
[_dashboardCollectionView setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:_dashboardCollectionView];
dataSource = [NSMutableArray arrayWithArray:#"your objects"];
}
#pragma mark - Collection View Datasource and Delegate Methods
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake( 22.0, 22.0, 22.0, 22.0);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
return 22.0f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
return 15.0f;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(312,150);
}
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return dataSource.count;
}
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
// Find the enum for this module and load the correct tile
self.modulesDataModel = [dataSource objectAtIndex:indexPath.item];
CellMaster * cell;
cell = (CellMaster *)[collectionView dequeueReusableCellWithReuseIdentifier:#"Reuse" forIndexPath:indexPath];
cell.tag = indexPath.item;
cell.iconImage.image = [UIImage imageNamed:#""];
cell.lblModuleName.text = self.modulesDataModel.moduleName;
cell.lblModuleName.textColor = self.modulesDataModel.color;
cell.btnInfo.tag = indexPath.item;
[cell.btnInfo addTarget:cell action:#selector(didPressInfoIcon:) forControlEvents:UIControlEventTouchUpInside];
cell.delegate = self;
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
// Enum for tile that was clicked
self.modulesDataModel = [dataSource objectAtIndex:indexPath.item];
}
Hope it would help you.
I made a little tweaks to your code and made it work with this:
You must manually initialize that array: meaning you have to say how big it's gonna be
#interface ViewController ()
#property (nonatomic) UIView *layoutView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.layoutView = [[UIView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.layoutView];
[self makeLayoutWithMinRow:0 maxRow:5 minColumn:0 maxColumn:5];
}
- (UIColor *)randomColor {
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
return color;
}
-(void)makeLayoutWithMinRow:(int)minRow maxRow:(int)maxRow minColumn:(int)minColumn maxColumn:(int)maxColumn {
NSInteger intLeftMargin = 10; // horizontal offset from the edge of the screen
NSInteger intTopMargin = 10; // vertical offset from the edge of the screen
NSInteger intYSpacing = 30; // number of pixels between the button origins (vertically)
NSInteger intXTile;
NSInteger intYTile;
NSInteger width;
id buttons[maxRow][maxColumn];
width = ((self.layoutView.frame.size.width-(maxColumn * 5))/maxColumn);
for (int y = minRow; y < maxRow; y++)
{
for (int x = minColumn; x < maxColumn; x++)
{
intXTile = (x * width) + intLeftMargin;
intYTile = (y * intYSpacing) + intTopMargin;
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
button.backgroundColor = [self randomColor];
buttons[x][y] = button;
[self.layoutView addSubview:buttons[x][y]];
}
}
}
#end
You are trying to create a button-array or something like that here?
UIButton *buttons[x][y] = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
What you really want to do is create the button object and then add it to an array (if you want to access it afterwards, otherwise it's enough to add it as a subview):
// Outside the for loop, probably as an instance variable or property:
NSMutableArray *buttons = [[NSMutableArray alloc] init];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(intXTile, intYTile, width, 15)];
[buttons addObject:button];
You may even need to put that buttons array inside another array to get the multidimensional aspect right, or use a NSMutableDictionary with corresponding keys.
I am building a ViewController just to show one image. I added the ImageView programmatically to a scroll view. I would like to allow the user to zoom in and out. This is my code
#interface ImageViewerViewController ()<UIScrollViewDelegate>
#property (nonatomic, strong) UIImageView *ImageView;
#property (weak, nonatomic) IBOutlet UIScrollView *Scroll;
#end
#implementation ImageViewerViewController
-(UIView*) viewForZoomingInScrollView{
return self.ImageView;
}
-(void) viewDidLoad{
self.Scroll.minimumZoomScale = 0.2;
self.Scroll.maximumZoomScale = 1.5;
self.Scroll.delegate = self;
NSLog(#"View did load");
if(self.imageName)
[self updateImage];
}
-(void)setImageName:(NSString *)imageName{
NSLog(#"set Image");
_imageName = imageName;
}
-(void)updateImage{
self.ImageView =[[UIImageView alloc]init];
self.ImageView.image = [UIImage imageNamed:self.imageName];
[self.ImageView sizeToFit];
self.Scroll.contentSize = self.imageName? self.ImageView.image.size: CGSizeZero;
[self.Scroll addSubview:self.ImageView];
}
#end
As you see, I already set the delegate of the scroll to self and I added the protocol header and the needed message.
But the zooming feature is not working.
Could you help me please?
I appreciate your time and efforts.
Regards,
This will work as I created a demo of it. If anything do else let me know.
-(void)viewDidLoad
{
float minimumScale = [_floorPlanImageView frame].size.width /[_floorPlanScrollView frame].size.width;
_floorPlanScrollView.maximumZoomScale = 5; //Change as per you need
_floorPlanScrollView.minimumZoomScale = minimumScale; //Change as you need
_floorPlanScrollView.zoomScale = minimumScale;
_floorPlanScrollView.delegate =self;
_floorPlanScrollView.clipsToBounds = YES;
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return _floorPlanImageView;
}
I am trying to add a page control to my scroll view, and have followed numerous web tutorials, the majority which use the same code as this tutorial. However, once I place the code into my project, even with me making changes to the code to try to make it work, it just doesn't. I have managed to make the code work for when the page control is pressed, however it just won't work for the page scrolling. My issue is similar to this, although the answers are of no help. Here is my code:
MainViewController.h
#interface MainViewController : UIViewController
{
UIScrollView *svCollegeMain;
UIScrollView *svCollegePage;
UIPageControl *pcCollege;
UIView *viewP1;
}
#property (nonatomic, retain) IBOutlet UIScrollView* svCollegeMain;
#property (nonatomic, retain) IBOutlet UIScrollView* svCollegePage;
#property (nonatomic, retain) IBOutlet UIPageControl * pcCollege;
- (IBAction)changePage;
#end
and MainViewController.m
#implementation MainViewController
#synthesize svCollegeMain, svCollegePage, pcCollege;
- (void)viewDidLoad
{
[super viewDidLoad];
self.svCollegeMain.contentSize = CGSizeMake(960, 332);
self.svCollegePage.contentSize = CGSizeMake(320, 500);
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
CGFloat pageWidth = 320;
int page = floor((svCollegeMain.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pcCollege.currentPage = page;
}
- (IBAction)changePage
{
CGRect frame;
frame.origin.x = self.svCollegeMain.frame.size.width * self.pcCollege.currentPage;
frame.origin.y = 0;
frame.size = self.svCollegeMain.frame.size;
[self.svCollegeMain scrollRectToVisible:frame animated:YES];
}
#pragma mark - View lifecycle
- (void)viewDidUnload
{
[super viewDidUnload];
self.svCollegeMain = nil;
self.svCollegePage = nil;
self.pcCollege = nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Just incase this makes any difference, my view is set out with a view, then a main scroll view and page control within this view, another view and scroll view (next to each other) within the main scroll view, and finally a final view in the second scroll view (all in IB, did not want too much code), and everything is linked up in IB.
I notice that your MainViewController doesn't declare itself as implementing UIScrollViewDelegate, so I also assume that you've forgotten to set it up as the delegate for the scroll view in IB (otherwise it wouldn't compile).
Since it has no delegate defined, the scroll view won't be calling your scrollViewDidScroll function.
Tim
Try this
HeaderFile:
#interface DemoPageControlViewController : UIViewController <UIScrollViewDelegate>
{
IBOutlet UIScrollView *scrollView;
IBOutlet UIPageControl *pageControl;
BOOL pageControlUsed;
NSMutableArray *imageArray;
int pageNumber;
}
#property (nonatomic, retain) UIScrollView *scrollView;
#property (nonatomic, retain) UIPageControl *pageControl;
#property (nonatomic, retain) NSMutableArray *imageArray;
- (IBAction) changePage:(id)sender;
Implementation File:
#import "DemoPageControlViewController.h"
#implementation DemoPageControlViewController
#synthesize pageControl, scrollView, imageArray;
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect frame;
frame.origin.x = 0;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.showsHorizontalScrollIndicator = NO;
imageArray = [[NSMutableArray alloc]init];
[imageArray addObject:#"small_one.png"];
[imageArray addObject:#"small_two.png"];
[imageArray addObject:#"small_three.png"];
[imageArray addObject:#"small_four.png"];
// add the last image to first
UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed: [imageArray objectAtIndex:([imageArray count] -1)]]];
imageView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height);
[self.scrollView addSubview:imageView];
[imageView release];
for(int i = 0; i < imageArray.count; i++)
{
UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:[imageArray objectAtIndex:i]]];
imageView.frame = CGRectMake((scrollView.frame.size.width * i ) + 320 , 0, scrollView.frame.size.width, scrollView.frame.size.height);
[self.scrollView addSubview:imageView];
[imageView release];
}
// add the first image to last
imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:[imageArray objectAtIndex:0]]];
imageView.frame = CGRectMake(scrollView.frame.size.width * ([imageArray count]+1), 0, scrollView.frame.size.width, scrollView.frame.size.height);
[self.scrollView addSubview:imageView];
[imageView release];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * ([imageArray count]+ 2), self.scrollView.frame.size.height);
[scrollView setContentOffset:CGPointMake(0, 0)];
[self.view addSubview:scrollView];
[self.scrollView scrollRectToVisible:CGRectMake(scrollView.frame.size.width,0,scrollView.frame.size.width,scrollView.frame.size.height) animated:NO];
}
- (IBAction)changePage :(id)sender
{
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage ;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
pageControlUsed = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
//pageControlUsed = NO;
NSLog(#"%f", self.scrollView.contentOffset.x);
CGFloat pageWidth = self.scrollView.frame.size.width;
//pageNumber = floor((self.scrollView.contentOffset.x - pageWidth / ([imageArray count]+2)) / pageWidth) + 1 ;
pageNumber = self.scrollView.contentOffset.x / pageWidth;
if(pageNumber == 0)
{
[self.scrollView scrollRectToVisible:CGRectMake((self.scrollView.frame.size.width * [imageArray count]), 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height) animated:NO];
pageNumber = [imageArray count];
//self.pageControl.currentPage = pageNumber;
}
else if(pageNumber == ([imageArray count]+1))
{
[self.scrollView scrollRectToVisible:CGRectMake(self.scrollView.frame.size.width, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height) animated:NO];
pageNumber = 1;
//self.pageControl.currentPage = pageNumber;
}
self.pageControl.currentPage = pageNumber - 1;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
}
This Code works fine. Try this