Methods for datasource are not called for this custom view - ios

I would like to implement this sort of thing :
1- So first, I have implemented this view : UnitSliderView :
using this code :
#import "UnitSliderView.h"
#implementation UnitSliderView
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self != nil)
{
//initialization
self.backgroundColor = [UIColor grayColor];
[self initViews];
[self initConstraints];
}
return self;
}
-(void)initViews
{
_leftLabel = [[UILabel alloc] init];
_leftLabel.textColor = [UIColor whiteColor];
//self.leftLabel.text = #"John";
[self addSubview:_leftLabel];
_rightLabel = [[UILabel alloc] init];
_rightLabel.textColor = [UIColor whiteColor];
//self.rightLabel.text = #"20%";
[self addSubview:self.rightLabel];
_slider = [[UISlider alloc] init];
_slider.value = 0.6;
[self addSubview:_slider];
}
-(void)initConstraints
{
self.rightLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.leftLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.slider.translatesAutoresizingMaskIntoConstraints = NO;
id views = #{
#"leftLabel": self.leftLabel,
#"slider": self.slider,
#"rightLabel": self.rightLabel,
};
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-[leftLabel(==90)]-5-[slider(==120)]-[rightLabel(==50)]-|" options:0 metrics:nil views:views]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.slider attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.leftLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.rightLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
}
#end
2- Then, I have created this view, named MultiSliderView, which use the precedent View (UnitSliderView):
#import "MultiSliderView.h"
#import "UnitSliderView.h"
static const int kUnitsCount = 3;
#implementation MultiSliderView
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self != nil)
{
//initialization
self.backgroundColor = [UIColor clearColor];
[self initViews];
}
return self;
}
- (void)initViews {
float totalHeight = self.frame.size.height;
float spacingRatio = 0.1;
float heightPerUnit = totalHeight/(kUnitsCount+spacingRatio*(kUnitsCount));
for (int i = 0; i < kUnitsCount; i++)
{
double percentage = [self.dataSource valueForSliderAtIndex:i];
NSString *leftString = [self.dataSource stringForLeftLabelAtIndex:i];
NSString *rightString = [self.dataSource stringForRightLabelAtIndex:i];
UnitSliderView *unit = [[UnitSliderView alloc] initWithFrame:CGRectMake(0, i*heightPerUnit + (i)*heightPerUnit*spacingRatio, self.frame.size.width, heightPerUnit)];
unit.slider.value = percentage;
unit.leftLabel.text = leftString;
unit.rightLabel.text = rightString;
[self addSubview:unit];
}
}
#end
3 - problem : when I init a MultiSlidersView in a viewController, the datasource methods that I have implemented in this same view controller are not called, thus the labels are not shown, and the slider values are 0.
I think there some of my code is not in the right place, but I can't find how to do it differently.

You should define the dataSource of the created class before you call the init function. You should define a method initWithFrame:(CGRect)frame andDataSource:(id <MultiSliderViewDataSource> ) dataSource and use it to initialize your view.

I assume you want to get an action called whenever the slide value changes. Since you implemented everything in code, you can do this in code using e.g.
[youSlider addTarget:self action:#selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];

Related

How to add UIButton on WKWebview?

I have two viewcontrollers which the viewcontroller1 has a NSTimer countdown to 0 and present viewcontroller2.
The viewcontroller2 has a wkwebview, and I also want to add UIButton on it.
Because I want to create a close button to dismiss viewcontroller2.
I try adding the UIButton on wkwebview, but I can't control it's NSlayoutConstrain.
What's wrong with my code?
Thanks.
red button is on right bottom.
// ViewController1.m
-(void)timerFired {
NSLog(#"===) self.count : %d", self.count);
if (self.count == 0) {
[self.timer invalidate];
self.timer = nil;
ViewController2 *vc = [[ViewController2 alloc] init];
[self presentViewController:vc animated:YES completion:nil];
} else {
self.count -= 1;
}
}
// ViewController2.m
#import "ViewController2.h"
#import <WebKit/WebKit.h>
#interface ViewController2 ()<WKScriptMessageHandler, WKNavigationDelegate,WKUIDelegate>
#property (nonatomic,strong) WKWebView* webView;
#property (nonatomic,strong) UIButton* button;
#property (nonatomic, strong) WKWebViewConfiguration * webConfig;
#end
#implementation ViewController2
- (void)viewDidLoad {
[super viewDidLoad];
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:[self createWKWebApp]];
[self.view addSubview: self.webView];
[self.webView.configuration.preferences setValue:#YES forKey:#"allowFileAccessFromFileURLs"];
self.webView.scrollView.bounces = NO;
[self.webView setContentMode:UIViewContentModeScaleAspectFit];
self.webView.navigationDelegate = self;
self.webView.UIDelegate = self;
NSURL *url = [NSURL URLWithString:#"https://stackoverflow.com/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
self.button = [UIButton buttonWithType: UIButtonTypeCustom];
self.button.translatesAutoresizingMaskIntoConstraints = false;
self.button.backgroundColor = UIColor.redColor;
[self.button setTitle:#"CLOSE" forState:UIControlStateNormal];
[self.button addTarget:self action:#selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.button];
NSLayoutConstraint *btnRight = [NSLayoutConstraint constraintWithItem:self.button attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:-20.0];
NSLayoutConstraint *btnTop = [NSLayoutConstraint constraintWithItem:self.button attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20.0];
NSLayoutConstraint *btnWidth = [NSLayoutConstraint constraintWithItem:self.button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1.0 constant:30.0];
NSLayoutConstraint *btnHeight = [NSLayoutConstraint constraintWithItem:self.button attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:30.0];
[self.view addConstraints:#[btnRight, btnTop, btnWidth, btnHeight]];
}
- (void)btnClicked:(UIButton *)sender {
NSLog(#"BTN CLICKED");
[self dismissViewControllerAnimated:false completion:nil];
}
- (WKWebViewConfiguration *)createWKWebApp {
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userContent = [[WKUserContentController alloc] init];
config.userContentController = userContent;
return config;
}
- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message {
NSString *name = message.name;
NSLog(#"===) message name = %#",name);
NSLog(#"===) body class = %#",[message.body class]);
}
You should konw the constraint like this
item1.attribute1 = multiplier × item2.attribute2 + constant
So the right constraint constant should be -20
NSLayoutConstraint *btnRight = [NSLayoutConstraint constraintWithItem:self.button attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:-20.0];
It might help you. Use these methods.
-(void)view.sendSubviewToBack(subview)
-(void)view.bringSubviewToFront(subview)
Usage:
[self.view sendSubviewToBack:webview];
[self.view bringSubviewToFront:button];

UIScrollView with horizontal paging` does not center subview

I am trying to use UIScrollView with paging enabled. I am adding various UIView to UISCrollView as a subviews. I want those subview to be smaller than size of scroll view so I have modified my constrains accordingly. Now when I actually swipe them left/ right then do not happened to be in center. I was expecting it to show previous / next view peeking from sides with current page in center.
This is what it looks like
Below is my code scrollview implementation
//
// ViewController.m
// Paging
//
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) UIScrollView *pagingScrollView;
#end
#implementation ViewController
- (UIScrollView *)pagingScrollView {
if (!_pagingScrollView) {
_pagingScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
_pagingScrollView.translatesAutoresizingMaskIntoConstraints = NO;
_pagingScrollView.backgroundColor = [UIColor orangeColor];
_pagingScrollView.showsHorizontalScrollIndicator = NO;
_pagingScrollView.showsVerticalScrollIndicator = NO;
_pagingScrollView.contentInset = UIEdgeInsetsZero;
_pagingScrollView.pagingEnabled = YES;
_pagingScrollView.clipsToBounds = NO;
_pagingScrollView.bounces = NO;
}
return _pagingScrollView;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self scrollViewSetUp];
NSDictionary *views = NSDictionaryOfVariableBindings(_pagingScrollView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[_pagingScrollView]|"
options:0
metrics:nil
views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[_pagingScrollView]|"
options:0
metrics:nil
views:views]];
}
- (void)scrollViewSetUp {
[self.view addSubview:self.pagingScrollView];
UIView *lastView = nil;
NSInteger arrayCount = 5;
for(NSInteger index = 0; index < arrayCount; index++)
{
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.translatesAutoresizingMaskIntoConstraints = NO;
view.backgroundColor = [UIColor yellowColor];
[self.pagingScrollView addSubview:view];
[self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.pagingScrollView
attribute:NSLayoutAttributeTop
multiplier:1
constant:40]];
[self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.pagingScrollView
attribute:NSLayoutAttributeHeight
multiplier:0.80
constant:0]];
[self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.pagingScrollView
attribute:NSLayoutAttributeWidth
multiplier:0.80
constant:0]];
if (lastView == nil && index == 0){
[self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-20-[view(==_pagingScrollView)]"
options:0
metrics:nil
views:#{#"view":view, #"_pagingScrollView":_pagingScrollView}]];
} else {
[self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:[lastView]-20-[view]"
options:0
metrics:nil
views:#{#"lastView":lastView, #"view":view, #"_pagingScrollView":_pagingScrollView}]];
}
if(index == arrayCount-1) {
[self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:[view]-20-|"
options:0
metrics:nil
views:#{#"view":view}]];
}
lastView = view;
}
}
#end
Any pointers/comments/feedback highly appreciated. Thanks.
Is this you want?
//
// ViewController.h
// Test
//
// Created by Lee on 7/8/16.
// Copyright © 2016 Lee. All rights reserved.
//
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (nonatomic, strong) UIScrollView *pagingScrollView;
#end
//
// ViewController.m
// Test
//
// Created by Lee on 7/8/16.
// Copyright © 2016 Lee. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()<UIScrollViewDelegate>
#property (nonatomic,strong)NSMutableArray *subviewsCenterArray;
#end
#implementation ViewController
- (UIScrollView *)pagingScrollView {
if (!_pagingScrollView) {
_pagingScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
_pagingScrollView.translatesAutoresizingMaskIntoConstraints = NO;
_pagingScrollView.backgroundColor = [UIColor orangeColor];
_pagingScrollView.showsHorizontalScrollIndicator = NO;
_pagingScrollView.showsVerticalScrollIndicator = NO;
_pagingScrollView.contentInset = UIEdgeInsetsZero;
_pagingScrollView.pagingEnabled = NO;
_pagingScrollView.clipsToBounds = NO;
_pagingScrollView.bounces = NO;
_pagingScrollView.delegate = self;
}
return _pagingScrollView;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self scrollViewSetUp];
NSDictionary *views = NSDictionaryOfVariableBindings(_pagingScrollView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[_pagingScrollView]|"
options:0
metrics:nil
views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[_pagingScrollView]|"
options:0
metrics:nil
views:views]];
}
- (void)scrollViewSetUp {
[self.view addSubview:self.pagingScrollView];
UIView *lastView = nil;
NSInteger arrayCount = 5;
_subviewsCenterArray = [NSMutableArray array];
for(NSInteger index = 0; index < arrayCount; index++)
{
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.translatesAutoresizingMaskIntoConstraints = NO;
view.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
view.tag = 9999;
view.layer.cornerRadius = 6;
[self.pagingScrollView addSubview:view];
[self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.pagingScrollView
attribute:NSLayoutAttributeTop
multiplier:1
constant:40]];
[self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.pagingScrollView
attribute:NSLayoutAttributeHeight
multiplier:0.80
constant:0]];
[self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.pagingScrollView
attribute:NSLayoutAttributeWidth
multiplier:0.80
constant:0]];
if (lastView == nil && index == 0){
[self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-20-[view(==_pagingScrollView)]"
options:0
metrics:nil
views:#{#"view":view, #"_pagingScrollView":_pagingScrollView}]];
} else {
[self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:[lastView]-20-[view]"
options:0
metrics:nil
views:#{#"lastView":lastView, #"view":view, #"_pagingScrollView":_pagingScrollView}]];
}
if(index == arrayCount-1) {
[self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:[view]-20-|"
options:0
metrics:nil
views:#{#"view":view}]];
}
[self.view layoutIfNeeded];
lastView = view;
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[self changeTheCardStatus:scrollView];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
[self changeTheCardStatus:scrollView];
}
-(void)changeTheCardStatus:(UIScrollView *)scrollView{
for (UIView *view in scrollView.subviews) {
if (view.tag == 9999) {
[_subviewsCenterArray addObject:#(view.center.x)];
}
}
CGFloat currentCenterOffsetX = scrollView.contentOffset.x + CGRectGetWidth(self.view.frame)/2.0;
NSMutableArray *absoluteValueArray = [NSMutableArray array];
NSMutableDictionary *absoluteValueDictionary = [NSMutableDictionary dictionary];
for (int i = 0; i < _subviewsCenterArray.count; i ++) {
float subviewsCenterPointX = [_subviewsCenterArray[i] floatValue];
double absolute = fabs(subviewsCenterPointX - currentCenterOffsetX);
[absoluteValueArray addObject:#(absolute)];
[absoluteValueDictionary setValue:#(subviewsCenterPointX) forKey:[NSString stringWithFormat:#"%f",absolute]];
}
[absoluteValueArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
double a = [obj1 doubleValue];
double b = [obj2 doubleValue];
if (a>b) {
return NSOrderedDescending;
}
else if (a<b){
return NSOrderedAscending;
}
else{
return NSOrderedSame;
}
}];
double shortValue = [absoluteValueArray.firstObject doubleValue];
double centerX = [[absoluteValueDictionary objectForKey:[NSString stringWithFormat:#"%f",shortValue]] doubleValue];
[UIView animateWithDuration:0.25 animations:^{
scrollView.contentOffset = CGPointMake(centerX - CGRectGetWidth(self.view.frame)/2.0, 0);
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Of course It's not. The subview of pagingScrollView doesn't have a right width! Also these subviews don's have correct horizontal margin.
First You should correct your setting width code, change the multiplier to 1 and constant to -40. Like this:
[self.pagingScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.pagingScrollView
attribute:NSLayoutAttributeWidth
multiplier:1
constant:-40]];
Then modify the subview margin, change -20 to -40, like this
[self.pagingScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:[lastView]-40-[view]"
options:0
metrics:nil
views:#{#"lastView":lastView, #"view":view, #"_pagingScrollView":_pagingScrollView}]];

How to add auto layout on UICollectionView programmatically?

I create a uicollectionview programmatically, and I want to add auto layout constraint on the collection view so that I can change the frame later. But the following code is not work.
I am trying to initialize the collectionview like this:
self.rootCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 100, self.bounds.size.width, self.bounds.size.height - 100) collectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];
self.rootCollectionView.dataSource = self;
self.rootCollectionView.delegate = self;
self.rootCollectionView.backgroundColor = [UIColor clearColor];
[self addSubview:self.rootCollectionView];
[self.rootCollectionView registerClass:[CASlideSwitchViewCell class] forCellWithReuseIdentifier:#"CASlideSwitchViewCell"];
self.topConstraint = 100;
float topCon = self.topConstraint;//self.topConstraint is a CGFloat property,
UICollectionView * cv = self.rootCollectionView;
cv.translatesAutoresizingMaskIntoConstraints = NO;
NSArray * constraintArray = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[cv]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(cv)];
NSArray *constraintArray2 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-topCon-[cv]-0-|" options:0 metrics:#{#"topCon":#(topCon)} views:NSDictionaryOfVariableBindings(cv)];
[self addConstraints:constraintArray];
[self addConstraints:constraintArray2];
then after I receive the data, I am trying to change topConstraint based on the data. Like this:
if (number <= 1) {
self.topScrollView.hidden = YES;
self.topConstraint = 0;
}else{
self.topScrollView.hidden = NO;
self.topConstraint = 100;
}
[self updateConstraints];
[self.rootCollectionView.collectionViewLayout invalidateLayout];
[self.rootCollectionView reloadData];
However, the top margin of the UICollectionView is always 100.
Do I miss something? Or it is not right to add auto layout like that?
The self.topConstraint is a float not a NSLayoutConstraint so you can not update the constraint. You can instead of using
NSArray *constraintArray2 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-topCon-[cv]-0-|" options:0 metrics:#{#"topCon":#(topCon)} views:NSDictionaryOfVariableBindings(cv)];
You should use
NSLayoutConstraint *topLayoutContraint = [NSLayoutConstraint constraintWithItem:cv
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:100];
NSArray *constraintArray2 = #[
topLayoutContraint,
[NSLayoutConstraint constraintWithItem:cv
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0]
];
then you can
if (number <= 1) {
self.topScrollView.hidden = YES;
topLayoutContraint.constant = 0;
} else {
self.topScrollView.hidden = NO;
topLayoutContraint.constant = 100;
}
[self setNeedsLayout];
[self.rootCollectionView reloadData];

Positioning UIButtons at top of Screen

What I want is to have 5 buttons equally spaced out at the top of the screen. I tried using constraints but the buttons would get squished.
I have this code so far:
- (void)viewDidLoad {
[super viewDidLoad];
//I know this is only two buttons
NSUInteger space = (_backround.frame.size.width - _squareOne.frame.size.width * 5) / 6;
CGRect newFrameOne;
newFrameOne = CGRectMake(space, 50, 55, 55);
CGRect newFrameTwo;
newFrameTwo = CGRectMake(space * 2 + _squareOne.frame.size.width, 50, 55, 55);
_squareOne.frame = newFrameOne;
_squareTwo.frame = newFrameTwo;
}
The buttons never show up... and I don't know any other ways to do this...
Any help?
Could you try something like this below?
Update: I've written the code properly using Xcode this time (previously I typed it from memory).
See below screenshot for the final result.
View Controller Header File
#interface ViewController : UIViewController
#property (nonatomic, strong) UIButton *btn1;
#property (nonatomic, strong) UIButton *btn2;
#property (nonatomic, strong) UIButton *btn3;
#property (nonatomic, strong) UIButton *btn4;
#property (nonatomic, strong) UIButton *btn5;
#end
View Controller Implementation File
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self initViews];
[self initConstraints];
}
-(void)initViews
{
self.btn1 = [[UIButton alloc] init];
self.btn1.backgroundColor = [UIColor grayColor];
self.btn2 = [[UIButton alloc] init];
self.btn2.backgroundColor = [UIColor grayColor];
self.btn3 = [[UIButton alloc] init];
self.btn3.backgroundColor = [UIColor grayColor];
self.btn4 = [[UIButton alloc] init];
self.btn4.backgroundColor = [UIColor grayColor];
self.btn5 = [[UIButton alloc] init];
self.btn5.backgroundColor = [UIColor grayColor];
[self.view addSubview:self.btn1];
[self.view addSubview:self.btn2];
[self.view addSubview:self.btn3];
[self.view addSubview:self.btn4];
[self.view addSubview:self.btn5];
}
-(void)initConstraints
{
self.btn1.translatesAutoresizingMaskIntoConstraints = NO;
self.btn2.translatesAutoresizingMaskIntoConstraints = NO;
self.btn3.translatesAutoresizingMaskIntoConstraints = NO;
self.btn4.translatesAutoresizingMaskIntoConstraints = NO;
self.btn5.translatesAutoresizingMaskIntoConstraints = NO;
id views = #{
#"btn1": self.btn1,
#"btn2": self.btn2,
#"btn3": self.btn3,
#"btn4": self.btn4,
#"btn5": self.btn5
};
// horizontal constraints
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-5-[btn1]-5-[btn2(==btn1)]-5-[btn3(==btn1)]-5-[btn4(==btn1)]-5-[btn5(==btn1)]-5-|" options:0 metrics:nil views:views]];
// vertical constraints
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.btn1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:5.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.btn2 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.btn1 attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.btn3 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.btn1 attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.btn4 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.btn1 attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.btn5 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.btn1 attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
}
Result
This is what I get.
What long black strip are you referring to, the battery indicator?

Using autolayout in UIScrollView subviews (programmatically)

First of all I've been reading all questions similar to this one, but with no success, so finally I'll try asking my specific case.
I have a UIScrollView that I fill with components programmatically this way:
- (void) fillScrollView(int numItems)
{
float posY = 10.0;
for(int i = 0; i < numItems; i++)
{
UIImageView *leftImg = [[UIImageView alloc] init];
[leftImg setTranslatesAutoresizingMaskIntoConstraints:NO];
[leftImg setFrame:CGRectMake(10.0, posY, 20.0, 20.0)];
[leftImg setImage:[UIImage imageNamed:#"img1"]];
UILabel *txtLb = [[UILabel alloc] init];
[txtLb setTranslatesAutoresizingMaskIntoConstraints:NO];
[txtLb setFont:[UIFont systemFontOfSize:15.0]];
[txtLb setNumberOfLines:0];
[txtLb setLineBreakMode:NSLineBreakByWordWrapping];
[txtLb setFrame:CGRectMake(40.0, posY, 240.0, 20.0)];
NSString *data = #"This is my example text, it could be longer.";
[txtLb setText:data];
CGRect paragraphRect = [dato boundingRectWithSize:CGSizeMake(txtLb.frame.size.width, 9999.0)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName: txtLb.font}
context:nil];
float height = paragraphRect.size.height;
CGRect frame = txtLb.frame;
frame.size.height = ceil(height);
[txtLb setFrame:frame];
UIImageView *rightImg = [[UIImageView alloc] init];
[rightImg setTranslatesAutoresizingMaskIntoConstraints:NO];
[rightImg setFrame:CGRectMake(290.0, posY, 20.0, 20.0)];
[rightImg setImage:[UIImage imageNamed:#"img2"]];
[_scrollV addSubview:leftImg];
[_scrollV addSubview:txtLb];
[_scrollV addSubview:rightImg];
height = height + 20.0;
if(height < 40.0) height = 40.0;
posY = posY + height;
}
[_scrollV setContentSize:CGSizeMake(_scrollV.frame.size.width, posY)];
}
I would like that theis constraints were:
H:|-10-[leftImg(20)]-10-[txtLb]-10-[rightImg(20)]-10-|
And vertically each row has a space of 10px of vertical separation from the row above.
I've tried using constraintWithItem but I'm confused about how to use it in this case.
Any help would be very appreciated. Kind regards!
EDIT
Following Zhang's suggestion I've put the 3 components inside a UIView. This way I can use autolayout between them without problems and everything is in the correct position inside each UIView.
However I'm still having problems using autolayout between UIViews inside the loop. I'm doing this:
All blocks have no left/right margin with the UIScrollView.
// 0px to the left of the UIScrollView
NSLayoutConstraint *constraintLeft = [NSLayoutConstraint constraintWithItem:block
attribute:NSLayoutAttributeLeftMargin
relatedBy:NSLayoutRelationEqual
toItem:_scrollV
attribute:NSLayoutAttributeRightMargin
multiplier:1.0
constant:0.0];
// 0px to the right of the UIScrollView
NSLayoutConstraint *constraintRight = [NSLayoutConstraint constraintWithItem:block
attribute:NSLayoutAttributeRightMargin
relatedBy:NSLayoutRelationEqual
toItem:_scrollV
attribute:NSLayoutAttributeLeftMargin
multiplier:1.0
constant:0.0];
[_scrollV addConstraint:constraintLeft];
[_scrollV addConstraint:constraintRight];
Regarding to the vertical separation between blocks, when the UIView is the first block of the UIScrollView:
// 10px below UIScrollView top
NSLayoutConstraint *constraintTop = [NSLayoutConstraint constraintWithItem:block
attribute:NSLayoutAttributeTopMargin
relatedBy:NSLayoutRelationEqual
toItem:_scrollV
attribute:NSLayoutAttributeBottomMargin
multiplier:1.0
constant:10.0];
[_scrollV addConstraint:constraintTop];
And when the UIView has any block above it:
// 10px below previous block
NSLayoutConstraint *constraintTop = [NSLayoutConstraint constraintWithItem:block
attribute:NSLayoutAttributeTopMargin
relatedBy:NSLayoutRelationEqual
toItem:previousBlock
attribute:NSLayoutAttributeBottomMargin
multiplier:1.0
constant:10.0];
[_scrollV addConstraint:constraintTop];
This shows all blocks without vertical separation, all in the same Y position, and also give errors applying constraints.
I'm sure I'm not using the right way constraintWithItem, but I can not find examples for this use.
It seems like you're trying to reinvent the wheel mate. You probably should be using UICollectionView or UITableView instead of UIScrollView and manually adding your cells.
Anyhow, for your scrollView method, one way you can implement it is like this:
ViewController Header File
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (nonatomic, strong) UIScrollView *scrollView;
#property (nonatomic, strong) UIView *contentView;
#end
ViewController Implementation File
#import "ViewController.h"
#import "Cell.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self initViews];
[self initConstraints];
[self fillScrollView:15];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)prefersStatusBarHidden
{
return YES;
}
-(void)initViews
{
self.scrollView = [[UIScrollView alloc] init];
// ------------------------------------------------------------------
// This content view will be the only child view of scrollview
// ------------------------------------------------------------------
self.contentView = [[UIView alloc] init];
// add content view to scrollview now
[self.scrollView addSubview:self.contentView];
// add scrollview to main view
[self.view addSubview:self.scrollView];
}
-(void)initConstraints
{
self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
id views = #{
#"scrollView": self.scrollView,
#"contentView": self.contentView
};
// setup scrollview constraints
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[scrollView]|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[scrollView]|" options:0 metrics:nil views:views]];
// ---------------------------------------
// setup content view constraint
//
// note: need to pin all four side of
// contentView to scrollView
// ---------------------------------------
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[contentView]|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[contentView]|" options:0 metrics:nil views:views]];
}
-(void)fillScrollView:(int) numItems
{
// clear any previous cells before adding new ones
[self.contentView.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
// Need to construct the layout visual format string
NSMutableString *strVerticalConstraint = [[NSMutableString alloc] init];
[strVerticalConstraint appendString:#"V:|"];
// this dictionary will hold all the key-value pair that identifies all the subviews
NSMutableDictionary *subviews = [[NSMutableDictionary alloc] init];
for(int i = 0; i < numItems; i++)
{
Cell *cell = [[Cell alloc] init];
// customize the cell's appearance here
cell.leftImage.image = [UIImage imageNamed:#"leftImage.png"];
cell.textLabel.text = #"This is my example text, it could be longer.";
cell.rightImage.image = [UIImage imageNamed:#"rightImage.png"];
[self.contentView addSubview:cell];
cell.translatesAutoresizingMaskIntoConstraints = NO;
id views = #{
#"cell": cell
};
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[cell]|" options:0 metrics:nil views:views]];
// prevent cell's width to extend beyond screen width
[self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1.0 constant:self.view.bounds.size.width]];
// cell name
NSString *cellName = [[NSString alloc] initWithFormat:#"cell%d", i];
// construct each cell's vertical constraint to add it strVerticalConstraint
NSString *viewName = nil;
if(i < numItems - 1)
{
viewName = [[NSString alloc] initWithFormat:#"[%#(50)]-10-", cellName];
}
else
{
viewName = [[NSString alloc] initWithFormat:#"[%#(50)]", cellName];
}
[strVerticalConstraint appendString:viewName];
// add cell name to dictionary
[subviews setValue:cell forKey:cellName];
}
[strVerticalConstraint appendString:#"|"];
NSLog(#"strVerticalConstraint: \n%#", strVerticalConstraint);
// Finally, use the long vertical constraint string
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:strVerticalConstraint options:0 metrics:nil views:subviews]];
}
#end
Cell Header File
#import <UIKit/UIKit.h>
#interface Cell : UIView
#property (nonatomic, strong) UIImageView *leftImage;
#property (nonatomic, strong) UILabel *textLabel;
#property (nonatomic, strong) UIImageView *rightImage;
#end
Cell Implementation File
#import "Cell.h"
#implementation Cell
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
[self initViews];
[self initConstraints];
}
return self;
}
-(void)initViews
{
self.backgroundColor = [UIColor grayColor];
self.leftImage = [[UIImageView alloc] init];
self.leftImage.contentMode = UIViewContentModeScaleAspectFill;
self.leftImage.clipsToBounds = YES;
self.leftImage.layer.cornerRadius = 10.0;
self.textLabel = [[UILabel alloc] init];
self.textLabel.numberOfLines = 0;
self.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.rightImage = [[UIImageView alloc] init];
self.rightImage.contentMode = UIViewContentModeScaleAspectFill;
self.rightImage.layer.cornerRadius = 10.0;
self.rightImage.clipsToBounds = YES;
[self addSubview:self.leftImage];
[self addSubview:self.textLabel];
[self addSubview:self.rightImage];
}
-(void)initConstraints
{
self.leftImage.translatesAutoresizingMaskIntoConstraints = NO;
self.textLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.rightImage.translatesAutoresizingMaskIntoConstraints = NO;
id views = #{
#"leftImage": self.leftImage,
#"textLabel": self.textLabel,
#"rightImage": self.rightImage
};
// horizontal constraints
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-10-[leftImage(20)]-10-[textLabel]-[rightImage(20)]-10-|" options:0 metrics:nil views:views]];
// vertical constraints
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.leftImage attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.rightImage attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:[leftImage(20)]" options:0 metrics:nil views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:[rightImage(20)]" options:0 metrics:nil views:views]];
}
#end
You should see something like this:
Maybe you have your reason's for using a scrollView and manually adding each row, otherwise, if you're open to alternative, you can use UICollectionView or UITableView.
The method above will result in a lot of memory use as you can imagine if you had 1000 rows, the app needs to calculate, rendering and store 1000 rows in memory. Not scalable, and not feasible.
That's where UITableView or UICollectionView comes in, they reuse each cell when it goes offscreen that way, you'll only ever need to render and store the visible cells on screen.
UICollectionView Demo
So, if you want to see a UICollectionView approach, this is a demo of how you can do it:
ViewController Header File
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
#property (nonatomic, strong) UICollectionView *collectionView;
#property (nonatomic, strong) NSArray *items;
#end
ViewController Implementation File
#import "ViewController.h"
#import "CustomCell.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self initViews];
[self initConstraints];
// --------------------------------------------------------
// Hardcoding 15 sample items as the data source.
// Your data might be from a JSON webservice REST API.
// --------------------------------------------------------
self.items = #[
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer.",
#"This is my example text, it could be longer."
];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)initViews
{
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.minimumInteritemSpacing = 0;
flowLayout.minimumLineSpacing = 10;
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
self.collectionView.backgroundColor = [UIColor whiteColor];
// need to tell CollectionView beforehand the cell class you want to use
[self.collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:#"cellID"];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
[self.view addSubview:self.collectionView];
}
-(void)initConstraints
{
self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
id views = #{
#"collectionView": self.collectionView
};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[collectionView]|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[collectionView]|" options:0 metrics:nil views:views]];
}
#pragma mark - UICollectionView Methods -
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.items.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
// note: reuse identifier must match what you specified in the register cell above
CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellID" forIndexPath:indexPath];
// ---------------------------------------------------------------
// hardcoding images here, you might load your images from JSON
// data using an image caching library like SDWebImage
// ---------------------------------------------------------------
cell.leftImage.image = [UIImage imageNamed:#"leftImage.png"];
// getting text data from data source "self.items"
cell.textLabel.text = self.items[indexPath.row];
cell.rightImage.image = [UIImage imageNamed:#"rightImage.png"];
return cell;
}
// ----------------------------------------------------------------
// Tells the collection view the width and height of each cell
// ----------------------------------------------------------------
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize size = CGSizeMake(self.view.frame.size.width, 50.0);
return size;
}
#end
CustomCell Header File
#import <UIKit/UIKit.h>
#interface CustomCell : UICollectionViewCell
#property (nonatomic, strong) UIImageView *leftImage;
#property (nonatomic, strong) UILabel *textLabel;
#property (nonatomic, strong) UIImageView *rightImage;
#end
CustomCell Implementation File
#import "CustomCell.h"
#implementation CustomCell
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
[self initViews];
[self initConstraints];
}
return self;
}
-(void)initViews
{
self.backgroundColor = [UIColor grayColor];
self.leftImage = [[UIImageView alloc] init];
self.leftImage.contentMode = UIViewContentModeScaleAspectFill;
self.leftImage.clipsToBounds = YES;
self.leftImage.layer.cornerRadius = 10.0;
self.textLabel = [[UILabel alloc] init];
self.textLabel.numberOfLines = 0;
self.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.rightImage = [[UIImageView alloc] init];
self.rightImage.contentMode = UIViewContentModeScaleAspectFill;
self.rightImage.layer.cornerRadius = 10.0;
self.rightImage.clipsToBounds = YES;
[self.contentView addSubview:self.leftImage];
[self.contentView addSubview:self.textLabel];
[self.contentView addSubview:self.rightImage];
}
-(void)initConstraints
{
self.leftImage.translatesAutoresizingMaskIntoConstraints = NO;
self.textLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.rightImage.translatesAutoresizingMaskIntoConstraints = NO;
id views = #{
#"leftImage": self.leftImage,
#"textLabel": self.textLabel,
#"rightImage": self.rightImage
};
// horizontal constraints
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-10-[leftImage(20)]-10-[textLabel]-[rightImage(20)]-10-|" options:0 metrics:nil views:views]];
// vertical constraints
[self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.leftImage attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
[self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
[self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.rightImage attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:[leftImage(20)]" options:0 metrics:nil views:views]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:[rightImage(20)]" options:0 metrics:nil views:views]];
}
#end
You end up with something like this:
Look the same but more efficient :D
No I didn't upload the same screenshot :P
Hope that helps?

Resources