Swift 3 - Create for loop UIButtons - for-loop

Hello guys, I create 14 buttons in for loop but each 7 buttons in one variable for example:
for i in 0...6 {
var button = UIButton()
...
var button2 = UIButton()
...
}
But I want create 14 buttons in one variable with for loop like in the picture:
In the picture I do it with two buttons in one for loop
And my sizes, xAxis and yAxis it must be :
let buttonWidth = self.view.frame.size.width / 7
var xAxis : CGFloat = 1
let yAxis : CGFloat = self.view.frame.size.height - (tileWidth * 2) - 100
let yAxis2 : CGFloat = self.view.frame.size.height - (tileWidth + 100)
So how can I create 14 button with using for loop with same sizes and axises ? like this :
for i in 0...13 {
var button = UIButton()
...
}

Edit
let emptySpace:CGFloat = 40 //how much you want (left + right)
var xAxis:CGFloat = emptySpace/2
let space:CGFloat = 2
let buttonWidth = ((self.view.frame.size.width)-((space*7)+emptySpace)) / 7
var yAxis : CGFloat = self.view.frame.size.height - (tileWidth * 2) - 100
let yAxis2 : CGFloat = self.view.frame.size.height - (tileWidth + 100)
for i in 1...14 {
let button = UIButton(type: .roundedRect)
button.frame = CGRect(x: xAxis, y: yAxis, width: buttonWidth, height: buttonWidth)
button.layer.cornerRadius = 10
xAxis = xAxis+buttonWidth+space
button.backgroundColor = UIColor.orange
view.addSubview(button)
if i%7 == 0 {
xAxis = emptySpace/2
yAxis = yAxis2+space
}
}

Related

How to show labels beside the bar in Char js 2?

I wanted to display the labels just like how it is done here, within chartjs documentation samples.
However, along with one label, I want to display another label beside the first label. Both the labels have different font colors. Something like this:
Is that possible? If yes, kindly let me know how can that be achieved.
Currently I am able to display one label using following code:
Chart.plugins.register({
afterDatasetsDraw: function(chart, easing) {
// To only draw at the end of animation, check for easing === 1
var ctx = chart.ctx;
chart.data.datasets.forEach(function (dataset, i) {
var meta = chart.getDatasetMeta(i);
if (!meta.hidden) {
meta.data.forEach(function(element, index) {
// Draw the text in black, with the specified font
ctx.fillStyle = 'rgb(0, 0, 0)';
var fontSize = 16;
var fontStyle = 'normal';
var fontFamily = 'Helvetica Neue';
ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
// Just naively convert to string for now
var dataString = dataset.data[index].toString();
// Make sure alignment settings are correct
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var padding = 5;
var position = element.tooltipPosition();
ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
});
}
});
}
});
Yes, that is possible. You can achieve that using the following chart plugin :
Chart.plugins.register({
afterDatasetsDraw: function(chart, ease) {
var barLabels = chart.options.barLabels;
if (!barLabels) return;
var ctx = chart.ctx;
chart.data.datasets.forEach(function(dataset, index) {
var meta = chart.getDatasetMeta(index);
if (!meta.hidden) {
meta.data.forEach(function(segment, index) {
var model = segment._model,
position = segment.tooltipPosition(),
x = position.x,
y = position.y,
height = model.height,
padding = height / 4;
ctx.save();
ctx.textBaseline = 'middle';
ctx.font = 'bold ' + height / 2 + 'px Arial';
ctx.fillStyle = '#777'; //first label's font color
var text1 = barLabels.first[index],
text2 = barLabels.second[index],
textWidth = ctx.measureText(text1).width + padding;
ctx.fillText(text1, x + padding, y);
ctx.fillStyle = '#000'; //second label's font color
ctx.fillText(text2, x + padding + textWidth, y);
ctx.restore();
});
}
});
}
});
To utilize the plugin, define the following properties in your chart options :
barLabels: {
first: ['0.4M', '1.6M', '0.6M', '0.7M', '1.5M'],
second: ['19.3%', '19.1%', '14.1%', '9.0%', '8.9%']
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
Chart.plugins.register({
afterDatasetsDraw: function(chart, ease) {
var barLabels = chart.options.barLabels;
if (!barLabels) return;
var ctx = chart.ctx;
chart.data.datasets.forEach(function(dataset, index) {
var meta = chart.getDatasetMeta(index);
if (!meta.hidden) {
meta.data.forEach(function(segment, index) {
var model = segment._model,
position = segment.tooltipPosition(),
x = position.x,
y = position.y,
height = model.height,
padding = height / 4;
ctx.save();
ctx.textBaseline = 'middle';
ctx.font = 'bold ' + height / 2 + 'px Arial';
ctx.fillStyle = '#777'; //first label's font color
var text1 = barLabels.first[index],
text2 = barLabels.second[index],
textWidth = ctx.measureText(text1).width + padding;
ctx.fillText(text1, x + padding, y);
ctx.fillStyle = '#000'; //second label's font color
ctx.fillText(text2, x + padding + textWidth, y);
ctx.restore();
});
}
});
}
});
var chart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'Statistics',
data: [1, 4, 2, 3, 4],
backgroundColor: ['#fd625e', '#01b8aa', '#01b8aa', '#01b8aa', '#fd625e'],
}]
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1,
max: 6
}
}]
},
barLabels: {
first: ['0.4M', '1.6M', '0.6M', '0.7M', '1.5M'],
second: ['19.3%', '19.1%', '14.1%', '9.0%', '8.9%']
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

Swift 2 how to expand and collapse a view?

I have scrollView in which if there is no data, I need to hide (collapse the space occupied by it) so that the lower view can come upwards.
I tried this code with no luck. Please help me.
if(dataForScroll==0){
var newFrame:CGRect = self.myScroll.frame;
newFrame.size.height = 0;
self.myScroll.frame = newFrame
}
A simple example with Swift 3 version, i think it might be solves your problem. Let me know if have any queries
#IBOutlet var mainScrollView: UIScrollView!
#IBOutlet var view1: UIView!
#IBOutlet var view2: UIView!
#IBOutlet var view3: UIView!
var data1 = NSArray()
var data2 = NSArray()
var data3 = NSArray()
func setFrame()
{
// data = Something you need to get
if data1.count == 0
{
self.view1.frame.size.height = 0
}
else
{
// return its actual height you need
}
if data2.count == 0
{
self.view2.frame.size.height = 0
}
else
{
// return its actual height you need
}
if data3.count == 0
{
self.view3.frame.size.height = 0
}
else
{
// return its actual height you need
}
var frame = self.view1.frame
frame.origin.y = 5
self.view1.frame = frame
frame = self.view2.frame
frame.origin.y = self.view1.frame.origin.y + self.view1.frame.size.height + 5
self.view2.frame = frame
frame = self.view3.frame
frame.origin.y = self.view2.frame.origin.y + self.view2.frame.size.height + 5
self.view3.frame = frame
var scrollHeight:CGFloat = 0.0
var contentRect:CGRect = CGRect.zero
for views in self.mainScrollView.subviews
{
let subView:UIView = views
contentRect = contentRect.union(subView.frame)
print(subView.frame.size.height)
scrollHeight = scrollHeight + subView.frame.size.height
}
self.mainScrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: scrollHeight + 20) // the "+ 20" reamains the spaces between the views, you can change as per your need
}

how to Horizontal box UIButtons?

I am required to make a view where number of buttons to be displayed will depend upon the argument to init. how can i make it possible horizontal box UIButtons?
override func viewDidLoad() {
var bs = 0;
for index in 1...20
{
bs+=50;var x = CGFloat(bs)
let button = UIButton(type: UIButtonType.System) as UIButton
button.contentMode = UIViewContentMode.ScaleToFill
button.frame = CGRectMake(x, 50, 40, 40) // X, Y, width, height
button.backgroundColor = UIColor.whiteColor()
button.setTitle("12", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(button);
}
}
i want to like this
You should probably look at UICollectionView
If you don't want to use a UICollectionView, I put up for you this small sample, on which you can try to build on, whether using a UIView or UIScrollView:
let view = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: 300, height: 300)))
view.backgroundColor = UIColor.redColor()
let buttonHeight = 40
let buttonWidth = 40
let marginInterCell = 10
let marginInterRow = 20
let numberOfButtonsInRow = 300/(buttonWidth + marginInterCell)
let totalNumberOfButtons = 20
for index in 0..totalNumberOfButtons {
let button = UIButton(type: UIButtonType.System) as UIButton
button.titleLabel?.text = "\(index)"
let x = (index % numberOfButtonsInRow) * (buttonWidth + marginInterCell) + marginInterCell/2
let y = (buttonHeight + marginInterRow) * (index / numberOfButtonsInRow) + marginInterRow/2
button.backgroundColor = UIColor.greenColor()
button.frame = CGRect(origin: CGPoint(x: x, y: y), size: CGSize(width: buttonWidth, height: buttonHeight))
view.addSubview(button)
}

Scrolling background with 3 images

My let´s:
let background = SKSpriteNode(imageNamed: "background1")
let background2 = SKSpriteNode(imageNamed: "background2")
let background3 = SKSpriteNode(imageNamed: "background3")
This is how i make the background scroll:
func makeBackground(){
var backgroundTexture = SKTexture(imageNamed: "background1")
var moveBackgroundByX = SKAction.moveByX(-backgroundTexture.size().width, y: 0, duration: 10)
var replaceBackground = SKAction.moveByX(backgroundTexture.size().width, y: 0, duration: 0)
var moveBackgroundForever = SKAction.repeatActionForever(SKAction.sequence([moveBackgroundByX, replaceBackground]))
for var i:CGFloat = 0; i < 3; i++ {
let background = SKSpriteNode(texture: backgroundTexture)
background.position = CGPoint(x: backgroundTexture.size().width/2 + (backgroundTexture.size().width * i), y: CGRectGetMidY(self.frame))
background.size.height = self.frame.height
background.runAction(moveBackgroundForever)
self.addChild(background)
}
}
Like this, it loops only background1, but i want it to scroll in order: "background1", "background2", "background3", and then "background1" again, and like that.

Add NSClickGestureRecognizer to NSButton programmatically swift

I have multiple NSButtons generated with this code:
var height = 0
var width = 0
var ar : Array<NSButton> = []
var storage = NSUserDefaults.standardUserDefaults()
height = storage.integerForKey("mwHeight")
width = storage.integerForKey("mwWidth")
var x = 0
var y = 0
var k = 1
for i in 1...height {
for j in 1...width {
var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30))
but.tag = k
but.title = ""
but.action = Selector("buttonPressed:")
but.target = self
but.bezelStyle = NSBezelStyle(rawValue: 6)!
ar.append(but)
self.view.addSubview(but)
x += 30
k++
}
y += 30
x = 0
}
And I need to add the NSClickGestureRecognizer to each of them to recognize secondary mouse button clicks. Is there any way to do that programmatically?
This should work:
let g = NSClickGestureRecognizer()
g.target = self
g.buttonMask = 0x2 // right button
g.numberOfClicksRequired = 1
g.action = Selector("buttonGestured:")
but.addGestureRecognizer(g)
and later
func buttonGestured(g:NSGestureRecognizer) {
debugPrintln(g)
debugPrintln(g.view)
if let v = g.view as? NSButton {
debugPrintln("tag: \(v.tag)")
}
}

Resources