Layout programmatically created UILabels in a UIView - swift

I have this:
Created via this piece of code:
// Add hashtag collection to a post
func addHashtags(container: UIView, constraint: NSLayoutConstraint) -> Void {
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width - 16 - 16
var currentOriginX: CGFloat = 0
var currentOriginY: CGFloat = 0
for j in 0..<self.pseudo.count {
if currentOriginY < 144 {
// Create a new label
let labelHashtag = RoundedLabel()
labelHashtag.rounded = true
tagLabels.append(labelHashtag)
print(tagLabels.count)
// Set its properties (title, colors, corners, etc)
labelHashtag.text = pseudo[j] as? String
labelHashtag.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
labelHashtag.textAlignment = .center
labelHashtag.textColor = UIColor.black
labelHashtag.backgroundColor = UIColor.white
labelHashtag.layer.borderColor = UIColor(red:0.88, green:0.88, blue:0.88, alpha:1.0).cgColor
labelHashtag.layer.borderWidth = 1
// Set its frame width and height
labelHashtag.frame.size.width = labelHashtag.intrinsicContentSize.width + tagPadding
labelHashtag.frame.size.height = tagHeight
// Add it to the scroll view
container.addSubview(labelHashtag)
// If current X + label width will be greater than container view width
// .. move to next row
if (currentOriginX + labelHashtag.frame.width > screenWidth) {
tagLabels[0].textColor = .red
print("übrig")
print(screenWidth - currentOriginX)
currentOriginX = 0
currentOriginY += tagHeight + tagSpacingY
}
// Set the btn frame origin
labelHashtag.frame.origin.x = currentOriginX
labelHashtag.frame.origin.y = currentOriginY
// Increment current X by btn width + spacing
currentOriginX += labelHashtag.frame.width + tagSpacingX
} else if currentOriginY == 90 {
}
// Update container view height
constraint.constant = currentOriginY + tagHeight
}
container.layoutIfNeeded()
}
I want to center all items in each row. I imagine I have to calculate the remaining width of my UIView and add a margin to the first item.
How can I add a margin to my UILabel? I can access it via tagLabels[0] and I think I know how to calculate the remaining width, but I don't know how I can add the margin to it.

Related

make disable , ui button random position swift

there is a UIButton in view controller and when button clicked , UIButton move with random position in View Controller . The question it is how i can make disable movable ability when clicked again on button ?
this is moveable Method :
func randomPosition() {
self.movable_Button.layer.cornerRadius = 10
let buttonWidth = movable_Button.frame.width
let buttonHeight = movable_Button.frame.height
let viewWidth = movable_Button.superview!.bounds.width
let viewHeight = movable_Button.superview!.bounds.height
let xwidth = viewWidth - buttonWidth
let yheight = viewHeight - buttonHeight
let xPosition = CGFloat(arc4random_uniform(UInt32(xwidth)))
let yPosition = CGFloat(arc4random_uniform(UInt32(yheight)))
movable_Button.center.x = xPosition + buttonWidth / 2
movable_Button.center.y = yPosition + buttonHeight / 2
}
I think you have programmed something like
func onButtonClicked() {
randomPosition()
}
so you can make a new variable:
var clickedButton = false
func onButtonClicked() { // i know this is not the correct function, but i think you know what i mean ;)
if clickedButton == false {
randomPosition()
} else {
clickedButton = true
}
}

How to add space between buttons in uiscrollview

I was trying so hard to add space between buttons array in UIScrollView but I couldn't make it. There is any way to make space between buttons array in UIScrollView ?
I have attached a picture explaining what I want.
This is my code :
//MARK: - SETUP CATEGORIES BUTTONS
func setupCategoriesButtons() {
var xCoord: CGFloat = 1
let yCoord: CGFloat = 1
let buttonHeight: CGFloat = 40
let buttonwidth: CGFloat = 40
let gap: CGFloat = 0
// Counter for items
var itemCount = 0
// Loop for creating buttons
for i in 0..<myArray.count {
itemCount = i
// Create a Button
let catButt = UIButton(type: .custom)
catButt.showsTouchWhenHighlighted = true
catButt.setTitle("\(myArray[itemCount])", for: .normal)
catButt.sizeToFit()
catButt.frame = CGRect(x: xCoord, y: yCoord, width: catButt.frame.size.width + 30, height: buttonHeight)
catButt.layer.cornerRadius = 8
catButt.titleLabel?.font = UIFont(name: "Titillium-Semibold", size: 12)
// catButt.addTarget(self, action: #selector(categoryButt(_:)), for: UIControlEvents.touchUpInside)
// Add Buttons & Labels based on xCood
xCoord += catButt.frame.size.width + gap
categoriesScrollView.addSubview(catButt)
letterButtons.append(catButt)
} // END LOOP --------------------------
for i in 0..<letterButtons.count {
letterButtons[i].tag = i
letterButtons[i].backgroundColor = RandomColor()
letterButtons[i].setTitleColor(UIColor.white, for: .normal)
}
// Place Buttons into the ScrollView
categoriesScrollView.contentSize = CGSize(width: buttonwidth * CGFloat(itemCount+1), height: yCoord)
}
let gap: CGFloat = 0
Looks wrong, if you want a gap. Shouldn't it be e.g. ... = 15?
Alternatives could include placing them in a UIStackView with a spacing set. This would also be simple using auto-layout, creating constraints between the buttons which provide the gaps.
Another suggestion:
I would suggest to use a UIStackView for achieving the desired appearance instead of adding the buttons directly in the scroll view. The gap would be represented as spacing property.
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .equalSpacing
// here is the "gap":
stackView.spacing = 16.0
therefore, you should add the buttons in it:
stackView.addArrangedSubview(button)

Multiple subviews being added to UIScrollview

On my users profile page, there is a scrollview users slide across to see more photos. Everything works with adding the photos but the problem is that each image added to the scrollviews subview, is added twice. This is the code I am using to populate the scrollview. I currently have an Imageview embed inside the scrollview on storyboard and use that as the default if user has no photos. The at the bottom should show the bug. I have tried using a combination of clipstobounds, scaleaspectfit, and setting background color to clear but nothing stops from showing an additional image in the background. Any ideas would be appreciated. On a side note, the bug is only noticed on the iphone 8 plus
var pages: Int = 1
var numPhotos: CGFloat = 1
var position: CGFloat = 1
let scrollWidth: CGFloat = profileImage.frame.width
let scrollHeight: CGFloat = profileImage.frame.height
let scrollY: CGFloat = profileImage.frame.origin.y
if let profileImg = user.profileImage {
profileResource = ImageResource(downloadURL: URL(string: profileImg)!, cacheKey: profileImg)
profileImage.kf.setImage(with: profileResource)
} else {
profileImage.image = #imageLiteral(resourceName: "requests_icon")
}
nameLbl.text = user.fullName
influenceLbl.text = "\(user.score)"
followersLbl.text = "\(user.followers)"
followingLbl.text = "\(user.following)"
if let image1 = user.photo1 {
let imageOne = UIImageView(frame: CGRect(x: scrollWidth * position, y: scrollY, width: scrollWidth, height: scrollHeight))
imageOne.contentMode = .scaleAspectFit
photo1Resource = ImageResource(downloadURL: URL(string: image1)!, cacheKey: image1)
imageOne.kf.setImage(with: photo1Resource)
pages = pages + 1
numPhotos = numPhotos + 1
position = position + 1
scrollView.addSubview(imageOne)
} else {
}
if let image2 = user.photo2 {
let imageTwo = UIImageView(frame: CGRect(x: scrollWidth * position, y: scrollY, width: scrollWidth, height: scrollHeight))
imageTwo.contentMode = .scaleAspectFit
photo2Resource = ImageResource(downloadURL: URL(string: image2)!, cacheKey: image2)
imageTwo.kf.setImage(with: photo2Resource)
pages = pages + 1
numPhotos = numPhotos + 1
position = position + 1
scrollView.addSubview(imageTwo)
} else {
}
if let image3 = user.photo3 {
let imageThree = UIImageView(frame: CGRect(x: scrollWidth * position, y: scrollY, width: scrollWidth, height: scrollHeight))
imageThree.contentMode = .scaleAspectFit
photo3Resource = ImageResource(downloadURL: URL(string: image3)!, cacheKey: image3)
imageThree.kf.setImage(with: photo3Resource)
pages = pages + 1
numPhotos = numPhotos + 1
position = position + 1
scrollView.addSubview(imageThree)
} else {
}
scrollView.contentSize = CGSize(width: profileImage.frame.width * numPhotos, height: scrollHeight)
scrollView.delegate = self
scrollView.contentMode = .scaleAspectFit
scrollView.clipsToBounds = true
pageControl.numberOfPages = pages
pageControl.currentPage = 0
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){
let pageWidth:CGFloat = scrollView.frame.width
let currentPage:CGFloat = floor((scrollView.contentOffset.x-pageWidth/2)/pageWidth) + 1
self.pageControl.currentPage = Int(currentPage)
}

How can I increase the y of a label, in swift?

So I am very new in Swift and I can't figure out how to increase the y value from a label.
I am trying to show in a label, some messages that a user types in an input... like a chat view.
So I have this code, but it puts all the messages one above the other:
I know that it is very messy, I am sorry for that.
Thanks!
//my label
#IBOutlet weak var label: UILabel!
//my text field
#IBOutlet weak var textF: UITextField!
#IBAction func buttonPressed(sender: AnyObject) {
//create a variable(input) to store my text from the TextField
var input = textF.text
//put that text in the label
label.text = input
var label2 : UILabel = UILabel(frame: CGRectMake(20, 20, 200, 21))
var isSendMessage: Bool = true {
didSet {
if isSendMessage {
var input = textF.text
label.text = input
textF.text = " "
// self.view.label.origin.y += 10
} else {
var input = textF.text
label2.text = input
textF.text = " "
}
}
}
label2.center = CGPointMake(160, 284)
label2.textAlignment = NSTextAlignment.Center
self.view.addSubview(label2)
//empty text field
textF.text = " "
label2.center = CGPointMake(160, 284)
label2.textAlignment = NSTextAlignment.Center
label2.text = input
//add it to the view
self.view.addSubview(label2)
}
Try this
Don't update Y axis directly as if your Y value is greater than the screen height then label will go off the screen.
Try the following code.
// Taking height and width of the screen
var height = UIScreen.mainScreen().bounds.size.height;
var width = UIScreen.mainScreen().bounds.size.width;
var x = 164.0 // Fixed height of the label
if x < height
{
x += 20.0 // Incrementing height value
if (height - 20) >= x // Checking the difference between screen height and x, so it doesn't go beyond the screen.
{
label.frame = CGRectMake(20.0, x, 200.0, 21.0)
self.view.addSubview(label)
}
else
{
// Setting default height
label.frame = CGRectMake(20.0,164.0, 200.0, 21.0)
self.view.addSubview(label)
}
}
Hope this will be helpful.
In a quick answer to your question, if you are just looking to change the position on the y-axis you can use the property .y under .center
self.yourLabel.center.y = self.yourLabel.center.y + 10

create an equal space between labels in the scrollview with swift

I am creating a menu of the same style as the kiosk play Application
I would like the same space between labels, for I dynamically creates, I try SEVERAL way but it does not work.
I size of their label and I added the padding but it does work.
Here is the result
here is my code
func menu (value: [String]){
var pos: CGFloat = 50.0
var index: Int = 0
for index = 0; index < value.count ; index++ {
self.titleLabel = UILabel()
self.titleLabel.text = "\(value[index])"
self.titleLabel.textColor = UIColor.blackColor()
self.titleLabel.backgroundColor = UIColor.blueColor()
self.titleLabel.font = UIFont(name: "MarkerFelt-Wide", size: 20)
self.titleLabel.sizeToFit()
//width of the label
var widhtLabel = self.titleLabel.frame.size.width
// add padding
self.titleLabel.frame.origin.x = widhtLabel + pos
self.scrollViewMenu.addSubview(self.titleLabel)
pos += 150.0
println()
}
self.scrollViewMenu.contentSize = CGSize(width: self.titleLabel.frame.origin.x + 220, height:0)
}
thanks