I am attempting to create a view to show a list of items and prices using two UILabels in a UIView.
In my UIViewController I call my subview LineItemView and pass data, and return the UIView to the main view that will hold the subviews.
Though my view is returning empty. The strings are null.
ViewController.m
#import "LineItemView.h"
//...
#property (weak, nonatomic) IBOutlet UIView *viewCharges;
//...
- (void)viewDidLoad {
[super viewDidLoad];
[self loadData];
}
- (void) loadData {
//Here we will fill in the viewCharges view
LineItemView * view = [[LineItemView alloc]init];
view.linePrice = #"1.00";
view.lineItem = #"Something";
[self.viewCharges addSubview:view];
}
LineItemView.h
#interface LineItemView : UIView {
UILabel * lblLineItem, *lblLinePrice;
}
#property (nonatomic,strong) NSString* lineItem;
#property (nonatomic,strong) NSString* linePrice;
LineItemView.m
#define LABEL_MINIMUM_HEIGHT 32
#define VERTICAL_MARGIN 5
#define HORIZONTAL_MARGIN 10
#implementation LineItemView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self createUI];
[self updateData];
NSLog(#"\n\n\n Line Item: %# Price: %# \n\n\n", self.lineItem, self.linePrice);
}
return self;
}
-(void) createUI {
lblLineItem = [[UILabel alloc] initWithFrame:CGRectZero];
lblLineItem.backgroundColor = [UIColor greenColor];
[self addSubview:lblLineItem];
lblLinePrice = [[UILabel alloc] initWithFrame:CGRectZero];
lblLinePrice.backgroundColor = [UIColor yellowColor];
[self addSubview:lblLinePrice];
}
- (void) updateLayout {
lblLineItem.frame = CGRectMake(HORIZONTAL_MARGIN, VERTICAL_MARGIN, 300, 35);
lblLinePrice.frame = CGRectMake(lblLineItem.frame.origin.x + lblLineItem.frame.size.width + HORIZONTAL_MARGIN, VERTICAL_MARGIN, 80, 35);
}
- (void) updateData {
lblLineItem.text = self.lineItem;
lblLinePrice.text = [NSString stringWithFormat:#"%0.2f", [self.linePrice floatValue]];
}
- (void) layoutSubviews {
[super layoutSubviews];
[self updateLayout];
}
What am I doing wrong?
If I want to continue calling LineItemView, how do I ensure that it is added below the previous one and ensure the viewCharges size is readjusted to fit all the subviews?
Solution using setters:
#implementation LineItemView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self createUI];
}
return self;
}
-(void) createUI {
lblLineItem = [[UILabel alloc] initWithFrame:CGRectZero];
lblLineItem.backgroundColor = [UIColor greenColor];
[self addSubview:lblLineItem];
lblLinePrice = [[UILabel alloc] initWithFrame:CGRectZero];
lblLinePrice.backgroundColor = [UIColor yellowColor];
[self addSubview:lblLinePrice];
}
- (void) updateLayout {
lblLineItem.frame = CGRectMake(HORIZONTAL_MARGIN, VERTICAL_MARGIN, 300, 35);
lblLinePrice.frame = CGRectMake(lblLineItem.frame.origin.x + lblLineItem.frame.size.width + HORIZONTAL_MARGIN, VERTICAL_MARGIN, 80, 35);
}
- (void) layoutSubviews {
[super layoutSubviews];
[self updateLayout];
}
- (void)setLineItem:(NSSTring *)lineItem {
_lineItem = lineItem;
lblLineItem.text = self.lineItem;
}
- (void)setLinePrice:(NSNumber *)linePrice {
_linePrice = linePrice;
lblLinePrice.text = [NSString stringWithFormat:#"%0.2f", [self.linePrice floatValue]];
}
Related
I have a custom UIView with a UICollectionView.
On screen rotation I am trying to get the UICollectionView to stretch across the screen, and then redraw its cells.
After I had the data downloaded I tried both [grid setNeedsLayout] and [grid setNeedsDisplay] but that didn't work.
This is what I want to happen:
Portrait
Landscape
(This is also how it appears when the app is started in landscape, but if you change to portrait it doens't update.)
But this is what I get if I start in Portrait mode and switch to Landscape.
I am creating these views programmatically. I am not using any Storyboards.
I have tried:
-(void)viewDidLayoutSubviews {
grid = [[MyThumbnailGridView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height/2, self.view.frame.size.width, self.view.frame.size.height/2)];
}
I have also tried toying with:
- (void) viewWillLayoutSubviews {
UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
if (UIInterfaceOrientationIsLandscape(interfaceOrientation))
{
//LANDSCAPE
if(grid){
NSLog(#"Grid Needs Landscape Layout");
grid.frame =CGRectMake(0, self.view.frame.size.height/2, self.view.frame.size.width, self.view.frame.size.height/2);
[grid refreshData];
}
}else {
//PORTRIAT
if(grid){
NSLog(#"Grid Needs Portrait Layout");
grid.frame =CGRectMake(0, self.view.frame.size.height/2, self.view.frame.size.width, self.view.frame.size.height/2);
[grid refreshData];
}
}
}
But I can't get it to stretch.
Any help?
MyThumbnailGridView
#interface ViewController () <UINavigationControllerDelegate> {
MyThumbnailGridView *grid;
NSMutableArray * arrImages;
}
- (void)viewDidLoad {
[super viewDidLoad];
arrImages = [NSMutableArray new];
grid = [[MyThumbnailGridView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height/2, self.view.frame.size.width, self.view.frame.size.height/2)];
//grid = [[MyThumbnailGridView alloc] initWithFrame:CGRectZero];
NSLog(#"showThumbnailGrid Grid View Size: %#", NSStringFromCGRect(grid.frame));
[self.view addSubview:grid];
[self getListOfImages];
}
-(void) getListOfImages {
//Do background task to get images and fill arrImages
[self onDownloadImageDataComplete];
}
- (void) onDownloadImageDataComplete{
grid.imageDataSource = arrImages;
// [grid setNeedsLayout];
// [grid setNeedsDisplay];
}
//...
#end
*MyThumbnailGridView.h
#interface MyThumbnailGridView : UIView
-(id)initWithFrame:(CGRect)frame;
-(void) refreshData;
#property (nonatomic,strong) NSArray *imageDataSource;
#end
*MyThumbnailGridView.m
#interface MyThumbnailGridView () <UICollectionViewDelegate, UICollectionViewDataSource>{
UICollectionView *collectionView;
}
#end
#implementation MyThumbnailGridView
- (instancetype) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self){
[self customInit];
}
return self;
}
- (void) customInit {
collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:[[MyFlowLayout alloc] init]];
collectionView.delegate = self;
collectionView.dataSource = self;
collectionView.allowsMultipleSelection = NO;
collectionView.showsVerticalScrollIndicator = YES;
[collectionView setBackgroundColor:[UIColor darkGrayColor]];
[collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:#"MyId"];
[self addSubview:collectionView];
}
- (void) refreshData {
NSLog(#"Refresh Grid Data");
[collectionView reloadData];
}
////other code
#end
MyFlowLayout
#interface MyFlowLayout : UICollectionViewFlowLayout
#end
#implementation MyFlowLayout
- (instancetype)init{
self = [super init];
if (self)
{
self.minimumLineSpacing = 1.0;
self.minimumInteritemSpacing = 1.0;
self.scrollDirection = UICollectionViewScrollDirectionVertical;
}
return self;
}
- (CGSize)itemSize {
NSInteger numberOfColumns = 3;
CGFloat itemWidth = (CGRectGetWidth(self.collectionView.frame) - (numberOfColumns - 1)) / numberOfColumns;
return CGSizeMake(itemWidth, itemWidth);
}
#end
MyCollectionViewCell
#interface MyCollectionViewCell : UICollectionViewCell
#property (strong, nonatomic) UIImageView *imageView;
#end
#implementation MyCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.imageView = [UIImageView new];
[self.imageView setContentMode:UIViewContentModeScaleAspectFill];
[self.imageView setClipsToBounds:YES];
[self.imageView setBackgroundColor:[UIColor darkGrayColor]];
[self.contentView addSubview:self.imageView];
}
return self;
}
- (void)prepareForReuse {
[super prepareForReuse];
self.imageView.image = nil;
[self.imageView setHidden:NO];
}
- (void)layoutSubviews {
[super layoutSubviews];
[self.imageView setFrame:self.contentView.bounds];
}
#end
This can be solved with
either you can change the frame of MyThumbnailGridView view in delegate function of orientation or create the view with constraints like this
(void)viewDidLoad {
[super viewDidLoad];
arrImages = [NSMutableArray new];
grid = [[MyThumbnailGridView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height/2, self.view.frame.size.width, self.view.frame.size.height/2)];
[self.view addSubview:grid];
[self getListOfImages];
}
-(void)viewDidLayoutSubviews
{
if(Once){
Once = NO;
// adding constraints
MyThumbnailGridView.translatesAutoresizingMaskIntoConstraints = NO;
[self.MyThumbnailGridView.widthAnchor constraintEqualToConstant:self.view.frame.size.width].active = YES;
[self.MyThumbnailGridView.heightAnchor constraintEqualToConstant:self.view.frame.size.height/2].active = YES;
[self.MyThumbnailGridView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor].active = YES;
[self.MyThumbnailGridView.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:self.view.frame.size.height/2].active = YES;
}
}
Also implement this
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[self.view layoutIfNeeded];
[MyThumbnailGridView.collectionView invalidate];
// Do view manipulation here.
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}
The problem is that the collection view itself is not changing size when the app rotates. You have given the collection view a fixed frame and then just walked away. So it never changes. So never lays itself out again.
You should give your MyThumbnailGridView and its collection view subview autolayout contraints to their superviews, so that they change size correctly when the app rotates.
I am trying to create a custom "alert view", nothing too fancy I just want to display a view overtop of the current view just like a UIAlertView.
Now here is the problem...I made the view in a nib file and now I want to alloc/init the view whenever I need to present an alert.Can anyone help me?
This is my attempt to get the view initialized...as of right now this crashes my app when I alloc/init a new alert view.
The app is crashing by telling me the view is not key-value compliant for the outlets.. I definitely have the outlets hooked up properly, unless I have a "File's Owner" thing screwed up.
NSObject 0x14e49800> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key....
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self load];
}
return self;
}
- (void)load {
NSArray *views = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil];
[self addSubview:[views firstObject]];
}
- (void)awakeFromNib {
[super awakeFromNib];
}
- (id)initWithFrame:(CGRect)frame
{
self = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil][0];
if (self) {
[self addSubview:self.contentView];
self.frame = frame;
}
return self;
}
- (instancetype)initWithTitle:(NSString *)title
message:(NSString *)message
delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
confirmButtonTitle:(NSString *)confirmButtonTitle {
self = [self initWithFrame:CGRectMake(0, 0, 320, 568)];
if (self) {
}
return self;
}
I made this method to present the view, just a simple addSubview...
- (void)showInView:(UIView *)view {
[view addSubview:self];
}
Try disabling autolayout and run the code.
Create a class same as below
#import "MyOverLay.h"
#interface MyOverLay (){
// control declarations
UIActivityIndicatorView *activitySpinner;
UILabel *loadingLabel;
}
#end
#implementation AcuOverLay
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)show:(NSString *)message{
// configurable bits
self.backgroundColor = [UIColor blackColor];
self.alpha = 0.75f;
self.autoresizingMask =UIViewAutoresizingFlexibleHeight;
float labelHeight = 22;
float labelWidth = self.frame.size.width - 20;
// derive the center x and y
float centerX = self.frame.size.width / 2;
float centerY = self.frame.size.height / 2;
// create the activity spinner, center it horizontall and put it 5 points above center x
activitySpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activitySpinner.frame = CGRectMake(centerX - (activitySpinner.frame.size.width / 2) , centerY - activitySpinner.frame.size.height - 20, activitySpinner.frame.size.width, activitySpinner.frame.size.height);
activitySpinner.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[self addSubview:activitySpinner];
[activitySpinner startAnimating];
// create and configure the "Loading Data" label
loadingLabel = [[UILabel alloc]initWithFrame:CGRectMake(centerX - (labelWidth / 2), centerY + 20 , labelWidth, labelHeight)];
loadingLabel.backgroundColor = [UIColor clearColor];
loadingLabel.textColor = [UIColor whiteColor];
loadingLabel.text = message;
loadingLabel.textAlignment = NSTextAlignmentCenter;
loadingLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[self addSubview:loadingLabel];
}
- (void)hide{
[UIView animateWithDuration:0.5 animations:^{
self.alpha = 0;
[self removeFromSuperview];
}];
}
#end
then create instance wherever you want
loadingOverlay = [[MyOverLay alloc]initWithFrame:[UIScreen mainScreen].bounds];
loadingOverlay.tag = 999;
[[[UIApplication sharedApplication] keyWindow] addSubview:loadingOverlay];
[loadingOverlay show:#"Saving ..."];
I need add all colors of my views to NSMuttableArray. A try do it, but adding only one color of last view. My Array named colorArray. Please help me.
I think it should be done in a loop, but I do not know exactly where its cause and how to describe it
It's my ViewController
#import "ViewController.h"
#import "RandomView.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize kol;
#synthesize sdvig1;
#synthesize sdvig2;
#synthesize myTextField;
#synthesize randView;
#synthesize redButton, greenButton, blueButton;
#synthesize colorArray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
kol=10;
}
return self;
}
-(void) viewWillAppear:(BOOL)animated
{
myTextField.delegate = self;
kol=[[myTextField text] intValue];
}
- (void)viewDidLoad
{
[super viewDidLoad];
myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width/4, 30)];
myTextField.backgroundColor=[UIColor yellowColor];
[myTextField setKeyboardType:UIKeyboardTypeNumberPad];
[self.view addSubview:myTextField];
redButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/4, 20, self.view.frame.size.width/4, 30)];
redButton.backgroundColor=[UIColor redColor];
[redButton addTarget: self
action: #selector(redSort:) forControlEvents: UIControlEventTouchUpInside];
greenButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/4*2, 20, self.view.frame.size.width/4, 30)];
greenButton.backgroundColor=[UIColor greenColor];
[greenButton addTarget: self
action: #selector(greenSort:) forControlEvents: UIControlEventTouchUpInside];
blueButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/4*3, 20, self.view.frame.size.width/4, 30)];
blueButton.backgroundColor=[UIColor blueColor];
[blueButton addTarget: self
action: #selector(blueSort:) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview:redButton];
[self.view addSubview:greenButton];
[self.view addSubview:blueButton];
[self createView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark- Создание и удаление View's
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[myTextField resignFirstResponder];
[self textFieldShouldReturn:myTextField];
myTextField.text = #"";
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if ([self.myTextField.text isEqualToString:#""]) {
} else
{
[self.myTextField resignFirstResponder];
kol=[[self.myTextField text] intValue];
[self removeView];
[self createView];
}
return YES;
}
-(void)createView{
colorArray= [[NSMuttableArray alloc] init];
sdvig1=self.view.frame.size.width/(2*(kol+5));
sdvig2=self.view.frame.size.height/(2*(kol+5));
randView = [[RandomView alloc] initWithFrame:CGRectMake(0,self.myTextField.frame.origin.y+self.myTextField.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-(self.myTextField.frame.origin.y+self.myTextField.frame.size.height)) count:kol sdvig:CGPointMake(sdvig1, sdvig2) vc:self];
[colorArray addObject:randView.backgroundColor]; //IT'S MY ARRAY
NSLog(#"colorArray= %#", colorArray);
[self.view addSubview:randView];
}
-(void) removeView{
[randView removeFromSuperview];
}
#pragma mark- Цвета
-(UIColor *) randomColor
{
CGFloat red = (CGFloat)arc4random() / (CGFloat)RAND_MAX;
CGFloat blue = (CGFloat)arc4random() / (CGFloat)RAND_MAX;
CGFloat green = (CGFloat)arc4random() / (CGFloat)RAND_MAX;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}
#end
And my View Class
//
// RandomView.m
// FewView
//
// Created by admin on 3/11/14.
// Copyright (c) 2014 admin. All rights reserved.
//
#import "RandomView.h"
#import "ViewController.h"
//#import <QuartzCore/QuartzCore.h>
#implementation RandomView
#synthesize randView;
//#synthesize myArray;
//#synthesize colorArrayRed, colorArrayBlue, colorArrayGreen, colorArray;
//#synthesize colorArray;
//CGFloat redBack, greenBack, blueBack, alphaBack;
- (id)initWithFrame:(CGRect)frame count:(NSInteger)kol sdvig:(CGPoint)sdvig vc:(ViewController*) delegat
{
self = [super initWithFrame:frame];
if (self)
{
// myArray = [[NSMutableArray alloc]init];
if (kol>0) {
[self setBackgroundColor:[delegat randomColor]];
randView = [[RandomView alloc] initWithFrame:CGRectMake(sdvig.x, sdvig.y, self. frame.size.width-2*sdvig.x, self.frame.size.height-2*sdvig.y) count:--kol sdvig:CGPointMake(sdvig.x, sdvig.y) vc:delegat];
self.layer.cornerRadius = 25;
self.layer.masksToBounds = YES;
[self addSubview:randView];
}
}
return self;
}
#end
Every time you call createView you're creating a new array. Try moving the colorArray = [[NSMutableArray alloc] init]; line into your viewDidLoad method.
I have 15 views with randomly color and I need to sort them by color. I click the sort button on red color and they are arranged from most to least red, and so needs to be done on the green and blue. How can I do this?
It's my ViewController
//
// ViewController.m
// FewView
//
// Created by admin on 3/11/14.
// Copyright (c) 2014 admin. All rights reserved.
//
#import "ViewController.h"
#import "RandomView.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize kol;
#synthesize sdvig1;
#synthesize sdvig2;
#synthesize myTextField;
#synthesize randView;
#synthesize redButton, greenButton, blueButton;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
kol=10;
}
return self;
}
-(void) viewWillAppear:(BOOL)animated{
myTextField.delegate = self;
kol=[[myTextField text] intValue];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if ([self.myTextField.text isEqualToString:#""]) {
} else
{
[self.myTextField resignFirstResponder];
kol=[[self.myTextField text] intValue];
[self removeView];
[self createView];
}
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width/4, 30)];
myTextField.backgroundColor=[UIColor yellowColor];
[myTextField setKeyboardType:UIKeyboardTypeNumberPad];
[self.view addSubview:myTextField];
redButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/4, 20, self.view.frame.size.width/4, 30)];
redButton.backgroundColor=[UIColor redColor];
[redButton addTarget: self
action: #selector(redSort:) forControlEvents: UIControlEventTouchUpInside];
greenButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/4*2, 20, self.view.frame.size.width/4, 30)];
greenButton.backgroundColor=[UIColor greenColor];
[greenButton addTarget: self
action: #selector(greenSort:) forControlEvents: UIControlEventTouchUpInside];
blueButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/4*3, 20, self.view.frame.size.width/4, 30)];
blueButton.backgroundColor=[UIColor blueColor];
[blueButton addTarget: self
action: #selector(blueSort:) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview:redButton];
[self.view addSubview:greenButton];
[self.view addSubview:blueButton];
[self createView];
}
-(void)createView{
sdvig1=self.view.frame.size.width/(2*(kol+5));
sdvig2=self.view.frame.size.height/(2*(kol+5));
randView = [[RandomView alloc] initWithFrame:CGRectMake(0,self.myTextField.frame.origin.y+self.myTextField.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-(self.myTextField.frame.origin.y+self.myTextField.frame.size.height)) count:kol sdvig:CGPointMake(sdvig1, sdvig2) vc:self];
[self.view addSubview:randView];
}
-(void) removeView{
[randView removeFromSuperview];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[myTextField resignFirstResponder];
[self textFieldShouldReturn:myTextField];
myTextField.text = #"";
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction)redSort:(id)sender{
NSLog(#"red");
}
-(IBAction)greenSort:(id)sender{
NSLog(#"gren");
}
-(IBAction)blueSort:(id)sender{
NSLog(#"blue");
}
//-(void) sortMyView{
// // randView = [[RandomView alloc] init];
// [randView.myArray sortUsingComparator:^( obj1, randView obj2)]{
// // сравниваем два объекта
// // и возвращаем YES или NO
// return YES;
// }];
//}
-(UIColor *) randomColor
{
CGFloat red = (CGFloat)arc4random() / (CGFloat)RAND_MAX;
CGFloat blue = (CGFloat)arc4random() / (CGFloat)RAND_MAX;
CGFloat green = (CGFloat)arc4random() / (CGFloat)RAND_MAX;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}
#end
And it my View Class
//
// RandomView.m
// FewView
//
// Created by admin on 3/11/14.
// Copyright (c) 2014 admin. All rights reserved.
//
#import "RandomView.h"
#import "ViewController.h"
#implementation RandomView
#synthesize randView;
#synthesize myArray;
- (id)initWithFrame:(CGRect)frame count:(NSInteger)kol sdvig:(CGPoint)sdvig vc:(ViewController*) delegat
{
self = [super initWithFrame:frame];
if (self)
{
if (kol>0) {
[self setBackgroundColor:[delegat randomColor]];
randView = [[RandomView alloc] initWithFrame:CGRectMake(sdvig.x, sdvig.y, self. frame.size.width-2*sdvig.x, self.frame.size.height-2*sdvig.y) count:--kol sdvig:CGPointMake(sdvig.x, sdvig.y) vc:delegat];
[self addSubview:randView];
myArray = [[NSMutableArray alloc]init];
[myArray addObject:randView];
NSLog(#"color %#", delegat.randomColor);
// NSLog(#"obj %#", myArray);
// NSLog(#"view= %#", randView);
}
}
return self;
}
#end
You can get the components of UIColor like this:
CGFloat *components = CGColorGetComponents(color);
Then get the RGB values:
components[0],components[1],components[2]
You have to write your own comparison logic. And then you can use 'NSSortDescriptor'
Refer this:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/Reference/Reference.html
I have a subclassed UITextView for placeholder and background image.
Here's the code
BKCUTextView.h
#import <UIKit/UIKit.h>
#interface BKCUTextView : UITextView
- (void)setPlaceholder:(NSString *)placeholder;
- (void)setPlaceholderColor:(UIColor *)placeholderColor;
- (void)setBackgroundImage:(UIImage *)img;
#end
BKCUTextView.m
#import "BKCUTextView.h"
#interface BKCUTextView()
{
NSString * _placeholder;
UIColor * _normalColor;
UIColor * _placeholderColor;
BOOL _needToShowPlaceholder;
UIImageView * _bgImageView;
}
#end
#implementation BKCUTextView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[self _initEvents];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
if(_needToShowPlaceholder) { [_placeholder drawAtPoint:CGPointMake(0, 0) withFont:self.font]; }
}
- (void)setTextColor:(UIColor *)textColor
{
_normalColor = textColor;
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
_placeholderColor = placeholderColor;
}
- (void)setPlaceholder:(NSString *)placeholder
{
_needToShowPlaceholder = YES;
_placeholder = placeholder;
}
-(void)setBackgroundImage:(UIImage *)img
{
if(_bgImageView == nil)
{
_bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
[self addSubview:_bgImageView];
[self sendSubviewToBack:_bgImageView];
[self bringSubviewToFront:self];
}
[_bgImageView setImage:img];
}
- (void)_initEvents
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(_textChanged:) name:UITextViewTextDidChangeNotification object:self];
}
-(void)_textChanged:(NSNotification *)noti
{
_needToShowPlaceholder = (self.text.length == 0);
if(_needToShowPlaceholder) { self.textColor = _placeholderColor; }
else { self.textColor = _normalColor; }
[self setNeedsDisplay];
}
instance
BKCUTextView * tv = [[BKCUTextView alloc] initWithFrame:CGRectMake(5, 55, 300, 50)];
[tv setBackgroundColor:[UIColor darkGrayColor]];
[tv setTextColor:[UIColor whiteColor]];
[tv setPlaceholderColor:[UIColor grayColor]];
[tv setPlaceholder:#"placeholder here!"];
[tv setBackgroundImage:[UIImage imageNamed:#"btn_coin_prs.png"]];
[self.view addSubview:tv];
[self.view bringSubviewToFront:tv];
each property - backgroundImage and placeholderText - works fine, but when I set them together, the placeholder is drawn under the backgroundImage.
How can I bring the text above the back image?
Try this method [self bringSubviewToFront:];
Hope it will help!