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!
Related
custom UITextField: In the click TextField input,After the keyborad popup,enter the background to get enter foreground again,The app crash!
if you don't click TextField input,background or foreground conversion ,It is normal;Part of the code:
#implementatio BKSearchViewController
- (void)setNavgationView {
BKSearchBar *searchBar = [[BKSearchBar alloc] initWithFrame:CGRectMake(20, 27, kScreenWidth - 90, 30)];
searchBar.placeholder = #"输入昵称/拜托号";
searchBar.delegate = self;
[searchBar setKeyboardType:UIKeyboardTypeDefault];
[searchBar setReturnKeyType:UIReturnKeySearch];
[searchBar setPlaceholderColor:kcallColor(#"a4a4a4")];
[searchBar setPlaceholderFont:kFont(14)];
[searchBar addTarget:self action:#selector(SearchTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[navgationView addSubview:searchBar];
}
#end
//BKSearchBar The key code
#implementation BKSearchBar
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 设置背景
self.backgroundColor = kcallColor(#"7d1d57");
self.returnKeyType = UIReturnKeySearch;
// 设置内容 -- 垂直居中
self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self UI];
}
return self;
}
- (void)UI{
// 设置左边显示一个放大镜
UIImageView *leftView = [[UIImageView alloc] init];
omit...
//右边的view
UIImageView *rightView = [[UIImageView alloc] init];
omit...
}
- (CGRect)placeholderRectForBounds:(CGRect)bounds{
CGRect rect = CGRectMake(self.leftView.right, (self.height - 24) / 2, bounds.size.width, 14);
return rect;
}
- (void)clearText{
self.text = nil;
}
- (void)setPlaceholderColor:(UIColor *)color{
[self setValue:color forKeyPath:#"_placeholderLabel.textColor"];
}
- (void)setPlaceholderFont:(UIFont *)font{
[self setValue:font forKeyPath:#"_placeholderLabel.font"];
}
Thank all!The problem is resolved!because of the runtime!
+ (void)swizzleInstanceMethod:(Class)class originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector
{
Method otherMehtod = class_getInstanceMethod(class, otherSelector);
Method originMehtod = class_getInstanceMethod(class, originSelector);
// 交换2个方法的实现
method_exchangeImplementations(otherMehtod, originMehtod);
}
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]];
}
How to get the black blocks disappear?
And after the rotation, the black blocks disappear.
AppDelegate Source File:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:#"ViewController"];
self.window.rootViewController = viewController;
bar = [KodUserCenterBar instance];
[self.window makeKeyAndVisible];
return YES;
}
Header File:
#interface KodUserCenterBar : UIWindow
/**获取单例
*/
+ (instancetype)instance;
/**显示工具栏
*/
+ (void)show;
/**隐藏工具栏
*/
+ (void)hide;
/**显示功能视图
*/
+ (void)showFunctionView;
/**隐藏功能视图
*/
+ (void)hideFunctionView;
#end
Source File:
#define WIDTH self.frame.size.width
#define HEIGHT self.frame.size.height
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kBarWidth 200
#define kBarImageViewTag 100
#define kBarItemGap 5
#define degreesToRadian(x) (M_PI * (x) / 180.0)
#interface KodUserCenterBarFunctionItemObject : NSObject
#property (nonatomic, copy) NSString *title;
#property (nonatomic, assign) NSUInteger indexOfTabBar;
#property (nonatomic, copy) NSString *imageName;
+ (instancetype)objectWithTitle:(NSString *)title indexOfTabBar:(NSUInteger)index imageName:(NSString *)imageName;
#end
#implementation KodUserCenterBarFunctionItemObject
+ (instancetype)objectWithTitle:(NSString *)title indexOfTabBar:(NSUInteger)index imageName:(NSString *)imageName
{
KodUserCenterBarFunctionItemObject *obj = [KodUserCenterBarFunctionItemObject new];
if (obj) {
obj.title = title;
obj.indexOfTabBar = index;
obj.imageName = imageName;
}
return obj;
}
#end
#interface KodUserCenterBar()
{
UIPanGestureRecognizer *pan;
UIViewController *_rootVC;
}
#property (nonatomic, copy) NSArray *itemsOfBar;
#property (nonatomic, assign) CGFloat initWidth;
#property (atomic, strong) UIButton *button;
#end
static KodUserCenterBar *static_instance = nil;
static BOOL isShowMenu = NO;
#implementation KodUserCenterBar
+ (instancetype)instance
{
if (static_instance == nil) {
static_instance = [KodUserCenterBar new];
[static_instance addTopButton];
}
return static_instance;
}
+ (void)show
{
[KodUserCenterBar instance].hidden = NO;
}
+ (void)hide
{
[KodUserCenterBar instance].hidden = YES;
}
+ (void)showFunctionView
{
if (!isShowMenu) {
[[KodUserCenterBar instance] clickBar:nil];
}
}
+ (void)hideFunctionView
{
if (isShowMenu) {
[[KodUserCenterBar instance] clickBar:nil];
}
}
- (instancetype)init
{
if (self = [super init]) {
self.backgroundColor = [UIColor clearColor];
self.windowLevel = UIWindowLevelAlert;
self.userInteractionEnabled = YES;
[self makeKeyAndVisible];
self.sd_x = 0;
self.sd_center_y = [UIScreen mainScreen].bounds.size.height / 2;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(onDeviceOrientationChange) name:UIDeviceOrientationDidChangeNotification object:nil];
}
return self;
}
- (NSArray *)itemsOfBar
{
if (_itemsOfBar == nil) {
KodUserCenterBarFunctionItemObject *item1 = [KodUserCenterBarFunctionItemObject objectWithTitle:#"个人中心" indexOfTabBar:0 imageName:#"tb3_toolbaruser"];
KodUserCenterBarFunctionItemObject *item2 = [KodUserCenterBarFunctionItemObject objectWithTitle:#"游戏礼包" indexOfTabBar:1 imageName:#"tb3_toolbargame"];
KodUserCenterBarFunctionItemObject *item3 = [KodUserCenterBarFunctionItemObject objectWithTitle:#"系统公告" indexOfTabBar:2 imageName:#"tb3_toolbarmsg"];
KodUserCenterBarFunctionItemObject *item4 = [KodUserCenterBarFunctionItemObject objectWithTitle:#"游戏论坛" indexOfTabBar:3 imageName:#"tb3_toolbarbbs"];
NSArray *data = #[item1, item2, item3, item4];
_itemsOfBar = [NSArray arrayWithArray:data];
}
return _itemsOfBar;
}
- (void)onDeviceOrientationChange
{
UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
if (orientation == UIDeviceOrientationPortrait || orientation == UIDeviceOrientationPortraitUpsideDown) {
NSLog(#"is portrait");
NSLog(#"width = %f, height = %f", kScreenWidth, kScreenHeight);
[self adjustWindowPosition];
self.sd_center_y = kScreenHeight / 2;
}
else if (orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight) {
NSLog(#"is landscape");
NSLog(#"width = %f, height = %f", kScreenWidth, kScreenHeight);
[self adjustWindowPosition];
self.sd_center_y = kScreenHeight / 2;
}
}
- (void)addTopButton
{
pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(dragBar:)];
pan.delaysTouchesBegan = NO;
[self addGestureRecognizer:pan];
UIViewController *vc = [[KodBasicViewController alloc] init];
vc.view.backgroundColor = [UIColor clearColor];
self.rootViewController = vc;
CGSize size = [UIImage imageNamed:#"tb3_assi_nor"].size;
self.sd_width = size.width;
self.sd_height = size.height;
self.initWidth = size.width;
_button = [[UIButton alloc] init];
[_button setBackgroundImage:[UIImage imageNamed:#"tb3_assi_nor"] forState:UIControlStateNormal];
[_button setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateHighlighted];
[_button setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateSelected];
_button.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[_button addTarget:self action:#selector(clickBar:) forControlEvents:UIControlEventTouchUpInside];
_button.userInteractionEnabled = YES;
_button.selected = NO;
[_button becomeFirstResponder];
[vc.view addSubview:_button];
}
- (void)clickBar:(id)button
{
NSTimeInterval interval = 0.2;
__weak typeof(_button) weakButton = _button;
isShowMenu = !isShowMenu;
pan.enabled = !isShowMenu;
if (self.sd_center_x > kScreenWidth / 2) {
[UIView animateWithDuration:interval animations:^{
self.sd_x = kScreenWidth;
} completion:^(BOOL finished) {
if (isShowMenu) {
self.sd_width = kBarWidth + self.initWidth;
_button.sd_right_x = self.sd_width;
UIImage *image = [UIImage imageNamed:#"tb3_assi_bor_right"];
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(1, 30, 1, 0)];
UIImageView *rightImageView = [[UIImageView alloc] initWithImage:image];
rightImageView.image = image;
rightImageView.sd_width = kBarWidth;
rightImageView.sd_right_x = _button.sd_x;
rightImageView.sd_center_y = _button.sd_center_y;
rightImageView.tag = kBarImageViewTag;
rightImageView.userInteractionEnabled = YES;
[self.rootViewController.view addSubview:rightImageView];
self.sd_x = kScreenWidth;
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_right"] forState:UIControlStateNormal];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_pre_right"] forState:UIControlStateSelected];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_pre_right"] forState:UIControlStateHighlighted];
[self addFunctionItems:NO];
}
else {
self.sd_width = self.initWidth;
_button.sd_right_x = self.sd_width;
UIView *contentView = [self.rootViewController.view viewWithTag:kBarImageViewTag];
[contentView removeFromSuperview];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_nor"] forState:UIControlStateNormal];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateSelected];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateHighlighted];
}
[UIView animateWithDuration:interval animations:^{
self.sd_right_x = kScreenWidth;
}];
}];
}
else {
[UIView animateWithDuration:interval animations:^{
self.sd_right_x = 0;
} completion:^(BOOL finished) {
if (isShowMenu) {
self.sd_width = kBarWidth + self.initWidth;
UIImage *image = [UIImage imageNamed:#"tb3_assi_bor_left"];
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(1, 0, 1, 30)];
UIImageView *leftImageView = [[UIImageView alloc] initWithImage:image];
leftImageView.image = image;
leftImageView.sd_width = kBarWidth;
leftImageView.sd_x = _button.sd_right_x;
leftImageView.sd_center_y = _button.sd_center_y;
leftImageView.tag = kBarImageViewTag;
leftImageView.userInteractionEnabled = YES;
[self.rootViewController.view addSubview:leftImageView];
self.sd_right_x = 0;
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_left"] forState:UIControlStateNormal];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_pre_left"] forState:UIControlStateSelected];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_act_pre_left"] forState:UIControlStateHighlighted];
[self addFunctionItems:YES];
}
else {
self.sd_width = self.initWidth;
UIView *contentView = [self.rootViewController.view viewWithTag:kBarImageViewTag];
[contentView removeFromSuperview];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_nor"] forState:UIControlStateNormal];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateSelected];
[weakButton setBackgroundImage:[UIImage imageNamed:#"tb3_assi_pre"] forState:UIControlStateHighlighted];
}
[UIView animateWithDuration:interval animations:^{
self.sd_x = 0;
}];
}];
}
}
- (void)addFunctionItems:(BOOL)isLeft
{
UIView *bgView = [self.rootViewController.view viewWithTag:kBarImageViewTag];
if (bgView) {
[self.itemsOfBar enumerateObjectsUsingBlock:^(KodUserCenterBarFunctionItemObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([bgView viewWithTag:idx] == nil) {
KodFrameTabBarItem *item = [[KodFrameTabBarItem alloc] init];
item.tag = idx;
item.title = obj.title;
item.imageName = obj.imageName;
item.sd_width = (bgView.sd_width - _itemsOfBar.count * kBarItemGap - 10) / _itemsOfBar.count;
item.sd_height = bgView.sd_height;
item.sd_center_y = bgView.sd_height / 2;
item.sd_center_x = kBarItemGap + idx * (item.sd_width + kBarItemGap) + item.sd_width / 2;
item.sd_center_x += isLeft ? 0 : item.sd_width / 4;
[item addTarget:self action:#selector(clickItem:) forControlEvents:UIControlEventTouchUpInside];
[bgView addSubview:item];
}
}];
}
}
- (void)clickItem:(id)sender
{
[KodNavigationView showWithIndex:0];
[[UIApplication sharedApplication].keyWindow addSubview:[KodNavigationView instance]];
}
- (void)adjustWindowPosition
{
if (self.sd_center_x < kScreenWidth / 2) {
self.sd_x = 0;
}
else {
self.sd_right_x = kScreenWidth;
}
}
- (void)dragBar:(UIPanGestureRecognizer *)p
{
CGPoint panPoint = [p locationInView:[[UIApplication sharedApplication] keyWindow]];
if (p.state == UIGestureRecognizerStateBegan) {
if (_button) {
_button.selected = YES;
}
}
else if(p.state == UIGestureRecognizerStateChanged) {
self.center = CGPointMake(panPoint.x, panPoint.y);
if (panPoint.x < WIDTH / 2) {
self.sd_x = 0;
}
else if (panPoint.x > kScreenWidth - WIDTH / 2) {
self.sd_right_x = kScreenWidth;
}
if (panPoint.y < HEIGHT / 2) {
self.sd_y = 0;
}
else if (panPoint.y > kScreenHeight - HEIGHT / 2) {
self.sd_bottom_y = kScreenHeight;
}
}
else if(p.state == UIGestureRecognizerStateEnded) {
if(panPoint.x <= kScreenWidth / 2) {
[UIView animateWithDuration:0.2 animations:^{
self.sd_x = 0;
} completion:nil];
}
else {
[UIView animateWithDuration:0.2 animations:^{
self.sd_right_x = kScreenWidth;
} completion:nil];
}
if (_button) {
_button.selected = NO;
}
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#end
Root ViewController
Source File Of Root ViewController:
#interface KodBasicViewController ()
#end
#implementation KodBasicViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
UIWindow *window = self.view.window;
[window bringSubviewToFront:window.rootViewController.view];
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
UIWindow *window = self.view.window;
[window bringSubviewToFront:window.rootViewController.view];
}
#end
Here is my solution to this problem:
window.layer.masksToBounds = true
It's the default background colour of UIWindow instance, and while your root view is doing rotation, those uncovered parts will be shown as black block as you said.
You can just set your desired background colour for your window (or make your root view's frame big enough to cover whole window while doing rotation, not recommended):
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
[self.window setBackgroundColor:[UIColor lightGrayColor]];
[self.window makeKeyAndVisible];
return YES;
}
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