I use this code to create a UISegment:
//segment controll
NSString *key2 = [allKeys2 objectAtIndex:i];
NSString *obj2 = [DictionaryHomework objectForKey:key2];
int val;
val = [obj2 intValue];
//segment controll
NSArray *itemArray2 = [NSArray arrayWithObjects: #"very easy", #"easy", #"ok", #"hard", #"challenging", nil];
UISegmentedControl *segmentedControl2 = [[UISegmentedControl alloc] initWithItems:itemArray2];
segmentedControl2.frame = CGRectMake(480, -60, 130, 350);
segmentedControl2.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl2.selectedSegmentIndex = val - 1;
[segmentedControl2 addTarget:self action:#selector(segmentedControlHomework:) forControlEvents:UIControlEventValueChanged];
segmentedControl2.transform =
CGAffineTransformRotate(segmentedControl2.transform, degreesToRadians(90));
NSArray *arr = [segmentedControl2 subviews];
for (int i = 0; i < [arr count]; i++) {
UIView *v = (UIView*) [arr objectAtIndex:i];
NSArray *subarr = [v subviews];
for (int j = 0; j < [subarr count]; j++) {
if ([[subarr objectAtIndex:j] isKindOfClass:[UILabel class]]) {
UILabel *l = (UILabel*) [subarr objectAtIndex:j];
l.transform = CGAffineTransformMakeRotation(- M_PI / 2.0); //do the reverse of what Ben did
}
}
}
[image1 addSubview:segmentedControl2];
segmentedControl2.tag = i;
[segmentArray addObject: segmentedControl2];
//segment control
On ios5 the control loads the titles in horizontal, while in ios6 in vertical. Why is this? has there been a change in iOS6?
You are fiddling with the inner mechanics of the UISegmentedControl. While you are not technically using private APIs, you are still accessing parts of UIKit that are not publicly documented.
One reason the behavior might have changed in iOS 6 could be that the segmented control now builds its subviews lazily in layoutSubviews ore some other place. It might even not use subviews at all. But I'm just making guesses here. However, it's Apple's choice to change undocumented internals of the framework.
Your code should never have been used in a shipping app. If you want to do something like this (vertical segments?) that the build-in segmented control can't do, build it on your own.
Related
I'm currently adding 5 textviews onto the viewcontroller programatically inside the viewDidLoad method.
for (int i = 0; i < 5; i++) {
//Add 5 textviews
UITextView *reqTV = [[UITextView alloc] initWithFrame:CGRectMake(30,30,250,50)];
reqTV.text = #"This is a textview";
[self.view addSubview:reqTV];
}
If later, I want to delete (not hide) these 5 textviews with a button click, how would I do that?
I have thought of using this, but am not sure how to call all 5 textviews to delete them.
- (void)removeTextViewButton:(id)sender {
[reqTV removeFromSuperview]; //remove textview
}
Thank you.
I see two easy ways:
You can save your textViews inside array as ivar of your controller.
And later remove each textView in array.
for (int i = 0; i < 5; i++) {
...
[textViews addObject: reqTV];
...
}
- (void)removeTextViewButton:(UIButton *)sender {
[textViews makeObjectsPerformSelector:#selector(removeFromSuperview)];
}
2. Assign static tag for each textView:
for (int i = 0; i < 5; i++) {
...
reqTV.tag = 1001; // for example
}
- (void)removeTextViewButton:(UIButton *)sender {
NSArray *subs = [NSArray arrayWithArray: self.view.subviews];
for (UIView *sub in subs) {
if (sub.tag == 1001) {
[sub removeFromSuperview];
}
}
}
Used code below to remove UITextViews:
- (void)removeTextViewButton:(id)sender {
NSArray *reqTVViews = [NSArray arrayWithArray: self.view.subviews];
for (UIView *tvView in reqTVViews) {
if ([tvView isKindOfClass:[UITextView class]]) {
[tvView removeFromSuperview];
}
}
}
When you are adding UITextFields on viewController use tag value to uniquely identify each textField.
You can store each tag value in an array for further use, eg.
#property (nonatomic, strong) NSMutableArray *tagArray;
NSMutableArray *tagArray = [NSMutableArray array];
for (int i = 101; i <= 105; i++ ) {
UITextField *txt = [UITextField alloc] init]; //for eg.
...
...
txt.tag = i;
[arr addObject:[NSNumber numberWithInt:i]];
[self.view addSubView:txt];
}
When you want to delete any of the textField or all then...
UIView *view = [self.view viewWithTag:<tag value>];
[view removeFromSuperview];
eg.
for (int i = 0; i < tagArray.count; i++) {
NSInteger tag = [[arr objectAtIndex:i] intValue];
UITextField *txt = (UITextField *)[self.view viewWithTag:tag];
[txt removeFromSuperview];
}
You can remove all subview in one go
- (void)removeTextViewButton:(id)sender
{
for (UIView *subview in views.subviews)
{
[subview removeFromSuperview];
}
}
Happy Coding.. :)
I am getting an exception in my iPhone-app,
-[__NSCFString sizeWithAttributes:]: unrecognized selector sent to instance,
when I start my app uner iOS6.1, under iOS7 or higher everything is OK.
The only difference between iOS6 and higher in my project are the XIBs. The error occurs when I press a button.
Maybe it comes from the different XIB, maybe not.
It looks like a memory leak, but i cant figure out why it happens.
The Exception occurrs when is try to calculate the size of a text from a button.
I set Exception-breakpoints to find the error.
Here some infos from the stacktrace:
In this method the error occurs:
- (float) calculateButtonWidth:(TypeButtonRest*) typeButtonRest{
UIFont *font = [UIFont boldSystemFontOfSize:16];
NSDictionary *userAttributes = #{NSFontAttributeName: font,
NSForegroundColorAttributeName: [UIColor blackColor]};
const CGSize textSize = [[typeButtonRest text] sizeWithAttributes: userAttributes];
...
The method is called from here:
- (ButtonMatrixInfos*) calculateButtonSchema:(NSMutableArray*) buttons screenWidth:(double)screenWidth minMargin:(double)minMargin{
ButtonMatrixInfos *returnValue = [[[ButtonMatrixInfos class] alloc] init];
int buttonCount = [buttons count];
[buttons retain];
for (int i=0; i < buttonCount; i++) {
float curWidth = [self calculateButtonWidth:[buttons objectAtIndex:i]];
maxButtonWidth = curWidth > maxButtonWidth ? curWidth : maxButtonWidth;
}
...
My assumption is, that buttons is corrupted. They are coming from here:
-(RadioButtonContainer*)addRadioButtons:(NSMutableArray *)buttons withButtonGroupName:(NSString*) groupName andMarginLeft:(int) marginLeft andMarginRight:(int) marginRight preselected:(NSString*) preselected {
ButtonListLayouter *bll = [[[[ButtonListLayouter class] alloc] init]retain];
ButtonMatrixInfos *bmi = [bll calculateButtonSchema:buttons screenWidth:(screenSize.width - marginLeft - marginRight) minMargin:5];
...
Created here:
NSMutableArray *buttonsRest = [[[NSMutableArray alloc] init]retain];
for (int i=0; i < [buttons count]; i++) {
TypeButtonRest *tpr = [[[[TypeButtonRest class] alloc] init]retain];
tpr.text = [[buttons objectAtIndex:i] objectForKey:#"value"];
tpr.key = [[buttons objectAtIndex:i] objectForKey:#"key"];
[buttonsRest addObject:tpr];
}
I hope this codefragments can help.
best regards
sizeWithAttributes is only available starting at iOS 7.0. You want to use sizeWithFont in iOS 6. Read more here
I'm trying to implement a graph (UIView) like this:
My current approach is to draw the rounded rects with UIBezierPath inside drawRect, store a pointer to every path in a private NSMutableArray and in my View Controller send a message to update the graph with the new value. (https://gist.github.com/gverri/f238ad17f90013bfc832)
But somehow I can't send a message to my view to change the colors of the paths.
.
I'm still a relative beginner and I'm sure I'm trying to reinvent the wheel somehow. Or just missing something obvious.
Should I redraw the graph at every update (1s ~ 2s)?! Should I use a special framework to do this?
Edit:
After digging a little I found out that I can't save a pointer to a path. After drawRect my pointers disappear from the array.
It seems I would need to use Core Graphics do make it work with this approach.
Is there an easier alternative?
I made a test app that uses a column view with 7 rounded rect subviews to implement the graph. Here's the ColumnView class (a subview of UIView),
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
NSMutableArray *temp = [NSMutableArray new];
_offColor = [UIColor colorWithRed:238/255.0 green:230/255.0 blue:238/255.0 alpha:1];
_onColor = [UIColor colorWithRed:154/255.0 green:102/255.0 blue:155/255.0 alpha:1];
for (int i=0; i<7; i++) {
UIView *roundRect = [[UIView alloc] initWithFrame:CGRectMake(0, i*34, frame.size.width -2, (frame.size.height/7) - 4)];
roundRect.backgroundColor = _offColor;
roundRect.layer.cornerRadius = 3;
[temp insertObject:roundRect atIndex:0];
[self addSubview:roundRect];
}
_columns = [NSArray arrayWithArray:temp];
}
return self;
}
-(void)setNumberOfDarkRects:(NSInteger) num {
[self.columns enumerateObjectsUsingBlock:^(UIView *sub, NSUInteger idx, BOOL *stop) {
if (idx + 1 <= num) {
sub.backgroundColor = self.onColor;
}else{
sub.backgroundColor = self.offColor;
}
}];
}
This is how I create the grid, and test updating the columns,
#interface ViewController ()
#property (strong,nonatomic) NSMutableArray *columns;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.columns = [NSMutableArray new];
for (int i=0; i<21; i++) {
ColumnView *column = [[ColumnView alloc] initWithFrame:CGRectMake(i * 22 + 10, 50, 22, 240)];
[self.view addSubview:column];
[self.columns addObject:column];
}
[self performSelector:#selector(doRandomColoring) withObject:nil afterDelay:2];
}
-(void)doRandomColoring {
for (ColumnView *col in self.columns) {
[col setNumberOfDarkRects:arc4random_uniform(8)];
}
[self performSelector:#selector(doRandomColoring) withObject:nil afterDelay:.2];
}
I`m having problem with removing view from superview.
Adding view:
- (void)createCircles
{
NSString *currentDate = [self currentDate];
NSArray *array = [self.horizontalScroll subviews];
UILabel *label = nil;
for (label in array)
{
if ([label.text isEqualToString:currentDate])
{
UIView *view = [[UIView alloc] initWithFrame:label.frame];
view.backgroundColor = [UIColor redColor];
[self.horizontalScroll insertSubview:view atIndex:0];
[self.labelsArray insertObject:view atIndex:0];
}
}
}
Trying to remove:
- (void)labelTouch:(UITapGestureRecognizer*)sender
{
NSArray *array = [self.horizontalScroll subviews];
UILabel *label = (UILabel*)sender.view;
for (int i = 0; i < [array count]; ++i)
{
UILabel *l = array[i];
if (label.tag == l.tag)
{
UIView *view = nil;
view = [self.labelsArray objectAtIndex:0];
view.hidden = YES;
[view removeFromSuperview];
view = nil;
[self.labelsArray removeObjectAtIndex:0];
}
}
}
But after touch view is still displaying. Tried to remove label (l) - it is removed
Try this,
[[[self.horizontalScroll subviews] objectAtIndex:0] removeFromSuperView];
You should store reference to this "unkillable" view in ivar or property. Initialize it in first method and call removeFromSupperView in second.
I'm hoping somebody can help me out here, I'm not sure what else to do. I have a UIScrollView that loads a set of 44 images, and then allows the user to page through them. My code was working, then suddenly it stopped. I have no idea what I have changed so any help would be much appreciated:
The previous view is a UITableView, it passes a string along with the name of the cell that was selected. Here is the ViewDidLoad Method from the ScrollView:
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:#"Answer"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(answerPressed:)];
self.navigationItem.rightBarButtonItem = rightButton;
if([questionSetName isEqualToString:#"Limitations"]){
[self limitationsView];
}
}
Here is the limitationsView:
-(void)limitationsView{
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, -44, self.view.frame.size.width, self.view.frame.size.height)];
scroll.pagingEnabled = YES;
NSArray *unsortedArray = [[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:#"Images/Limitations"];
NSMutableArray *limitationImages = [[NSMutableArray alloc] init];
for (int x = 0; x<[unsortedArray count]; x++) {
NSString *fileName = [[unsortedArray objectAtIndex:x] lastPathComponent];
[limitationImages insertObject:fileName atIndex:x];
}
NSArray *sortedArray = [limitationImages sortedArrayUsingFunction:finderSortWithLocal
context:(__bridge void *)([NSLocale currentLocale])];
for(int i = 0; i< [sortedArray count]; i++){
CGFloat xOrigin = i * self.view.bounds.size.width;
UIImageView *limitationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];;
[limitationImageView setImage:[UIImage imageNamed:[sortedArray objectAtIndex:i]]];
limitationImageView.contentMode = UIViewContentModeScaleAspectFit;
[scroll addSubview:limitationImageView];
}
scroll.contentSize = CGSizeMake(self.view.frame.size.width * [sortedArray count], self.view.frame.size.height);
[self.view addSubview:scroll];
}
When I get to the end of the LimitationsView method the sortedArray contains all 44 images, and the proper names, if I try and set the background color of the scrollview I can successfully do that. but my images are not loading and I am at a loss as to why?
I would suggest using
NSLog(#"image:%#",[UIImage imageNamed:[limitationsArray objectAtIndex:i]]);
to see if the image is null at that point. If that's the case, then there is a problem with the strings you are storing in that array i.e., they are not identical to the actual names of your images