Edit- how can I get UIlabel to get in the middle of the container? - swift

how can i get UIlabel to get in the middle of the container? and that text and view disappear equally and come to the next view.
EDIT: This code is working fine for me now
class TestViewController: UIViewController {
let container = UIView()
let redSquare = UIView()
let blueSquare = UIView()
let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
self.label.textColor = UIColor.orange
self.label.font = label.font.withSize(25)
self.label.numberOfLines = 0
self.label.center = self.blueSquare.center
self.label.textAlignment = NSTextAlignment.center
self.label.text =
"sosdihfiosdfhsdhfdisfhsdfhdsoifhsdofhsdifhdsofhdsofhsdohdsfdosdohdfh"
self.blueSquare.addSubview(label)
self.label.frame = CGRect(x: 45, y: 120, width: 300, height: 100)
self.container.frame = CGRect(x: 7, y: 200, width: 400, height: 500)
self.view.addSubview(container)
self.redSquare.frame = CGRect(x: 0, y: 0, width: 400, height: 500)
self.blueSquare.frame = redSquare.frame
self.redSquare.backgroundColor = UIColor.darkGray
self.blueSquare.backgroundColor = UIColor.darkGray
self.container.addSubview(self.redSquare)
}

Define two labels like:
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
let label2 = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
then inside viewDidLoad() before adding redSquare to container fix some labels's property and add label's to blue and red square:
label.center = self.redSquare.center
label.textAlignment = NSTextAlignment.center
label.text = "same text"
label2.textAlignment = NSTextAlignment.center
label2.center = self.blueSquare.center
label2.text = "same text"
self.blueSquare.addSubview(label2)
self.redSquare.addSubview(label)

Related

How to change UITextField RightView size?

I trying put to 2 items in rightView component. for example;`
let label = UILabel(frame: CGRect(x: -80, y: 0, width: 100, height: 50))
let rightView = UIView(frame: CGRect(x: 100, y: 100, width: 200, height: 100))
label.text = String(self.availableBalance) + " β‚Ί"
label.textColor = Colors.INVEST_RED
label.textAlignment = .center
let imageView = UIImageView(frame: CGRect(x: -100, y: 15, width: 20, height: 20))
imageView.image = UIImage(named: "full_balance_button")
rightView.addSubview(imageView)
rightView.addSubview(label)
let tap = UITapGestureRecognizer(target: self, action:#selector(tapGesture))
label.addGestureRecognizer(tap)
label.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tap)
imageView.isUserInteractionEnabled = true
rightView.addGestureRecognizer(tap)
rightView.isUserInteractionEnabled = true
rightView.backgroundColor = .white
textField.rightView = rightView
textField.rightViewMode = .always
But I can't change size rightView.

Swift error: Execution was interrupted reason: EXC_BREAKPOINT

I renamed a file. No errors appeared in my code but yet received this message. Help please! Error given (not sure why stack asks me for more info, but I have tried all things to resolve the issue eg, DerivedData, making a new playgrounds, ect) (I can't input my whole code here unfortunately, would really appreciate the help because I'm still relatively new to Swift and I don't even know what's EXC_BREAKPROINT(code=1) error is about despite googling for solutions.)
Affected Code:
Let intro = IntroViewController()
import Foundation
import PlaygroundSupport
import UIKit
public class IntroViewController: UIViewController {
func onMain(_ block: #escaping () -> Void) {
DispatchQueue.main.async(execute: block)
}
var previousBtn: UIButton!
var nextBtn: UIButton!
var pageLabel: UILabel!
var pages = [UIView]()
var pageNum = 0
let slide = UIImageView(frame: CGRect(x: 40, y: 350, width: 350, height: 250))
let slide2 = UIImageView(frame: CGRect(x: 40, y: 310, width: 350, height: 250))
var secondView: UIView = {
let view = UIView(frame: CGRect(x: 20, y: 20, width: 410, height: 600))
let headerLabel = UILabel(frame: CGRect(x: 40, y: 50, width: 300, height: 100))
headerLabel.font = UIFont.systemFont(ofSize: 30, weight: .bold)
headerLabel.textColor = Colors.Fonts.blackDefault
headerLabel.text = "So...what is Mental health about? πŸ€”"
headerLabel.numberOfLines = 2
let descriptionLabel = UILabel(frame: CGRect(x: 40, y: 150, width: 300, height: 120))
descriptionLabel.font = UIFont.systemFont(ofSize: 18, weight: .medium)
descriptionLabel.textColor = Colors.Fonts.blackDefault
descriptionLabel.text = """
Mental health consists of...
- Physical well-being 🏌️
- Emotional well-being 🀯
- Psychological well-being 🧠
And many more!
"""
descriptionLabel.numberOfLines = 7
let description2Label = UILabel(frame: CGRect(x: 40, y: 250, width: 350, height: 130))
description2Label.font = UIFont.systemFont(ofSize: 17, weight: .medium)
description2Label.textColor = Colors.Fonts.blackDefault
description2Label.text = "It affects how we think, act, handle stress and make choices."
description2Label.numberOfLines = 0
let img = UIImageView(frame: CGRect(x: 40, y: 400, width: 300, height: 150))
img.image = #imageLiteral(resourceName: "graph1.jpg")
view.addSubview(headerLabel)
view.addSubview(descriptionLabel)
view.addSubview(description2Label)
view.addSubview(img)
let subviews = view.subviews
for view in subviews {
view.isHidden = true
}
return view
}()
var thirdView: UIView = {
let view = UIView(frame: CGRect(x: 20, y: 20, width: 410, height: 600))
let headerLabel = UILabel(frame: CGRect(x: 40, y: 10, width: 300, height: 100))
headerLabel.font = UIFont.systemFont(ofSize: 30, weight: .bold)
headerLabel.textColor = Colors.Fonts.blackDefault
headerLabel.text = "How does it affects people? πŸ•ΊπŸ™‹"
headerLabel.numberOfLines = 2
let directedGraph = UILabel(frame: CGRect(x: 40, y: 100, width: 350, height: 50))
directedGraph.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
directedGraph.textColor = Colors.Fonts.blackDefault
directedGraph.text = "Mental Health affects people from all ages. From young πŸ§‘ till old πŸ§‘β€πŸ¦³"
directedGraph.numberOfLines = 5
let directedDescription = UILabel(frame: CGRect(x: 40, y: 150, width: 350, height: 50))
directedDescription.font = UIFont.systemFont(ofSize: 15, weight: .medium)
directedDescription.textColor = Colors.Fonts.blackDefault
directedDescription.text = "Positive and Negative mindset could affect mental health in many ways!"
directedDescription.numberOfLines = 10
let img11 = UIImageView(frame: CGRect(x: 50, y: 200, width: 350, height: 150))
img11.image = #imageLiteral(resourceName: "img1.1.png")
let weightedGraph = UILabel(frame: CGRect(x: 40, y: 350, width: 350, height: 50))
weightedGraph.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
weightedGraph.textColor = Colors.Fonts.blackDefault
weightedGraph.text = "Stats: Suicide rates in Asia (Teenage)"
weightedGraph.numberOfLines = 2
let weightedDescription = UILabel(frame: CGRect(x: 40, y: 400, width: 350, height: 50))
weightedDescription.font = UIFont.systemFont(ofSize: 15, weight: .medium)
weightedDescription.textColor = Colors.Fonts.blackDefault
weightedDescription.text = "the attached picture shown below is a chart that shows teen deaths caused by suicide in 2016."
// credits WHO
weightedDescription.numberOfLines = 6
let img2 = UIImageView(frame: CGRect(x: 80, y: 450, width: 300, height: 200))
img2.image = #imageLiteral(resourceName: "pic2.png")
view.addSubview(headerLabel)
view.addSubview(directedGraph)
view.addSubview(directedDescription)
view.addSubview(weightedGraph)
view.addSubview(weightedDescription)
view.addSubview(img2)
view.addSubview(img11)
let subviews = view.subviews
for view in subviews {
view.isHidden = true
}
return view
}()
var fourthView: UIView = {
let view = UIView(frame: CGRect(x: 20, y: 20, width: 410, height: 600))
let headerLabel = UILabel(frame: CGRect(x: 40, y: 20, width: 300, height: 100))
headerLabel.font = UIFont.systemFont(ofSize: 30, weight: .bold)
headerLabel.textColor = Colors.Fonts.blackDefault
headerLabel.text = "How can you πŸš€ your mental health?"
headerLabel.numberOfLines = 2
let descriptionLabel = UILabel(frame: CGRect(x: 40, y: 100, width: 300, height: 150))
descriptionLabel.font = UIFont.systemFont(ofSize: 15, weight: .medium)
descriptionLabel.textColor = Colors.Fonts.blackDefault
descriptionLabel.text = "There are many ways to improve your mental health! Such as exercising πŸ•Ί, playing your favorite sport 🏌️. But most importantly, eating well and getting adequate sleep is very important as having enough sleep can lower the risk of mental health problems"
descriptionLabel.numberOfLines = 0
let img = UIImageView(frame: CGRect(x: 5, y: 250, width: 400, height: 250))
img.image = #imageLiteral(resourceName: "manybrainslawls.png")
let explain = UILabel(frame: CGRect(x: 40, y: 500, width: 300, height: 100))
explain.font = UIFont.systemFont(ofSize: 15, weight: .medium)
explain.textColor = Colors.Fonts.blackAmount
explain.textAlignment = .center
explain.text = "Continuing on πŸš€πŸ§ "
explain.numberOfLines = 0
view.addSubview(headerLabel)
view.addSubview(descriptionLabel)
view.addSubview(img)
view.addSubview(explain)
let subviews = view.subviews
for view in subviews {
view.isHidden = true
}
return view
}()
var fifthView: UIView = {
let view = UIView(frame: CGRect(x: 20, y: 20, width: 410, height: 600))
let headerLabel = UILabel(frame: CGRect(x: 40, y: 20, width: 300, height: 100))
headerLabel.font = UIFont.systemFont(ofSize: 30, weight: .bold)
headerLabel.textColor = Colors.Fonts.blackDefault
headerLabel.text = "Part 2 πŸš€πŸ§ !"
headerLabel.numberOfLines = 1
let explain = UILabel(frame: CGRect(x: 40, y: 100, width: 300, height: 100))
explain.font = UIFont.systemFont(ofSize: 20, weight: .medium)
explain.textColor = Colors.Fonts.blackDefault
explain.text = "Besides from doing your favorite activities...here's what you can do to relieve stress & anxiety πŸ˜„!"
explain.numberOfLines = 0
let home = UILabel(frame: CGRect(x: 40, y: 210, width: 300, height: 50))
home.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
home.textColor = Colors.Fonts.blackDefault
home.text = "Be positive! Nothing is impossible! πŸ“ˆ"
home.numberOfLines = 2
let access = UILabel(frame: CGRect(x: 40, y: 270, width: 300, height: 50))
access.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
access.textColor = Colors.Fonts.blackDefault
access.text = "Get a diary! πŸ“"
access.numberOfLines = 1
let friends = UILabel(frame: CGRect(x: 40, y: 310, width: 300, height: 50))
friends.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
friends.textColor = Colors.Fonts.blackDefault
friends.text = "MediTatE! 🧎"
friends.numberOfLines = 1
let plant = UILabel(frame: CGRect(x: 40, y: 350, width: 300, height: 50))
plant.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
plant.textColor = Colors.Fonts.blackDefault
plant.text = "Talk to a friend! πŸ‘―πŸ—£"
plant.numberOfLines = 1
let approaches = UILabel(frame: CGRect(x: 40, y: 400, width: 300, height: 100))
approaches.font = UIFont.systemFont(ofSize: 15, weight: .medium)
approaches.textColor = Colors.Fonts.blackAmount
approaches.text = "Continuing on...πŸ’­"
approaches.numberOfLines = 0
view.addSubview(headerLabel)
view.addSubview(explain)
view.addSubview(home)
view.addSubview(access)
view.addSubview(friends)
view.addSubview(plant)
view.addSubview(approaches)
let subviews = view.subviews
for view in subviews {
view.isHidden = true
}
return view
}()
var sixthView: UIView = {
let view = UIView(frame: CGRect(x: 20, y: 20, width: 410, height: 600))
let headerLabel = UILabel(frame: CGRect(x: 40, y: 20, width: 320, height: 100))
headerLabel.font = UIFont.systemFont(ofSize: 36, weight: .bold)
headerLabel.textColor = Colors.Fonts.blackDefault
headerLabel.text = "undone"
headerLabel.numberOfLines = 1
let history = UILabel(frame: CGRect(x: 40, y: 100, width: 320, height: 100))
history.font = UIFont.systemFont(ofSize: 20, weight: .medium)
history.textColor = Colors.Fonts.blackDefault
history.text = "-"
history.numberOfLines = 0
let explain = UILabel(frame: CGRect(x: 40, y: 220, width: 320, height: 100))
explain.font = UIFont.systemFont(ofSize: 20, weight: .medium)
explain.textColor = Colors.Fonts.blackDefault
explain.text = "-"
explain.numberOfLines = 0
let img3 = UIImageView(frame: CGRect(x: 40, y: 350, width: 350, height: 250))
img3.image = #imageLiteral(resourceName: "img3.jpeg")
view.addSubview(headerLabel)
view.addSubview(history)
view.addSubview(explain)
view.addSubview(img3)
let subviews = view.subviews
for view in subviews {
view.isHidden = true
}
return view
}()
var seventhView: UIView = {
let view = UIView(frame: CGRect(x: 20, y: 20, width: 410, height: 600))
let headerLabel = UILabel(frame: CGRect(x: 40, y: 20, width: 350, height: 100))
headerLabel.font = UIFont.systemFont(ofSize: 30, weight: .bold)
headerLabel.textColor = Colors.Fonts.blackDefault
headerLabel.text = "Stress management tips! 🀩"
headerLabel.numberOfLines = 1
let history = UILabel(frame: CGRect(x: 40, y: 100, width: 310, height: 180))
history.font = UIFont.systemFont(ofSize: 15, weight: .medium)
history.textColor = Colors.Fonts.blackDefault
history.text =
"""
here are 5 tips that could help you relieve stress in tough situations (eg. Examinations, Presentations, ect)
1. Before the examintion/presentation, take a deeeeep breath! (inhale & exhale 🧘)
2.
4.
5.
"""
history.numberOfLines = 0
let slide = UIImageView(frame: CGRect(x: 40, y: 310, width: 350, height: 250))
slide.image = #imageLiteral(resourceName: "graph6_0.png")
view.addSubview(headerLabel)
view.addSubview(history)
view.addSubview(slide)
let subviews = view.subviews
for view in subviews {
view.isHidden = true
}
return view
}()
var eigthView: UIView = {
let view = UIView(frame: CGRect(x: 20, y: 20, width: 410, height: 600))
let headerLabel = UILabel(frame: CGRect(x: 40, y: 20, width: 350, height: 100))
headerLabel.font = UIFont.systemFont(ofSize: 36, weight: .bold)
headerLabel.textColor = Colors.Fonts.blackDefault
headerLabel.text = "Conclusion πŸŽ‰πŸ₯³"
headerLabel.numberOfLines = 1
let explore = UILabel(frame: CGRect(x: 40, y: 100, width: 350, height: 150))
explore.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
explore.textColor = Colors.Fonts.blackDefault
explore.text = "It is totally normal for us humans to feel upset, angry and dissapointed at ourselves"
explore.numberOfLines = 3
let run = UILabel(frame: CGRect(x: 40, y: 200, width: 350, height: 150))
run.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
run.textColor = Colors.Fonts.blackDefault
run.text = "No matter what, do your best and have a lil faith in ourselves! Thanks for reading! πŸ˜†"
run.numberOfLines = 3
view.addSubview(headerLabel)
view.addSubview(explore)
view.addSubview(run)
let subviews = view.subviews
for view in subviews {
view.isHidden = true
}
return view
}()
var firstView: UIView = {
let view = UIView(frame: CGRect(x: 20, y: 20, width: 410, height: 600))
let headerLabel = UILabel(frame: CGRect(x: 40, y: 50, width: 300, height: 100))
headerLabel.font = UIFont.systemFont(ofSize: 30, weight: .bold)
headerLabel.textColor = Colors.Fonts.blackDefault
headerLabel.text = "What is Mental Health about? πŸ€”"
headerLabel.numberOfLines = 2
let basicLabel = UILabel(frame: CGRect(x: 40, y: 250, width: 350, height: 40))
basicLabel.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
basicLabel.textColor = Colors.Fonts.blackDefault
basicLabel.text = "How does it affect people πŸ•ΊπŸ™‹?"
basicLabel.numberOfLines = 2
let mw2Label = UILabel(frame: CGRect(x: 40, y: 300, width: 350, height: 40))
mw2Label.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
mw2Label.textColor = Colors.Fonts.blackDefault
mw2Label.text = "How can you πŸš€ your mental health?"
mw2Label.numberOfLines = 2
let mw3Label = UILabel(frame: CGRect(x: 40, y: 350, width: 350, height: 40))
mw3Label.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
mw3Label.textColor = Colors.Fonts.blackDefault
mw3Label.text = "Stress management tips! 🀩"
mw3Label.numberOfLines = 2
let endLabel = UILabel(frame: CGRect(x: 40, y: 400, width: 300, height: 40))
endLabel.font = UIFont.systemFont(ofSize: 25, weight: .semibold)
endLabel.textColor = Colors.Fonts.blackDefault
endLabel.text = "Conclusion πŸŽ‰πŸ₯³"
view.addSubview(headerLabel)
view.addSubview(basicLabel)
view.addSubview(mw2Label)
view.addSubview(mw3Label)
view.addSubview(endLabel)
return view
}()
func slideShow2() {
var num = 0
while runSlideShow2, isAnimating {
onMain {
self.slide2.removeFromSuperview()
self.pages[6].addSubview(self.slide2)
}
num = (num + 1) % 4
usleep(250 * 1_000)
if !(runSlideShow2 && isAnimating) {
break
}
usleep(250 * 1_000)
if !(runSlideShow2 && isAnimating) {
break
}
usleep(250 * 1_000)
if !(runSlideShow2 && isAnimating) {
break
}
usleep(250 * 1_000)
}
self.slide2.removeFromSuperview()
}
func slideShow() {
var num = 0
while runSlideShow, isAnimating {
onMain {
self.slide.removeFromSuperview()
self.pages[5].addSubview(self.slide)
}
num = (num + 1) % 6
usleep(250 * 1_000)
if !(runSlideShow && isAnimating) {
break
}
usleep(250 * 1_000)
if !(runSlideShow && isAnimating) {
break
}
usleep(250 * 1_000)
if !(runSlideShow && isAnimating) {
break
}
usleep(250 * 1_000)
}
self.slide.removeFromSuperview()
}
let myqueue = DispatchQueue(label: "myQQ", attributes: [])
var isAnimating = false
var runSlideShow = false
var runSlideShow2 = false
#objc func nextTapped() {
pageNum += 1
if isAnimating {
isAnimating = false
}
onMain {
if self.pageNum == 7 {
self.nextBtn.isHidden = true
}
if self.pageNum == 1 {
self.previousBtn.isHidden = false
}
if self.pageNum == 5 {
self.runSlideShow = true
} else {
self.runSlideShow = false
}
if self.pageNum == 6 {
self.runSlideShow2 = true
} else {
self.runSlideShow2 = false
}
self.pageLabel.text = "Page \(self.pageNum + 1)"
self.pages[self.pageNum - 1].removeFromSuperview()
self.view.addSubview(self.pages[self.pageNum])
}
let prevSubs = pages[pageNum - 1].subviews
for view in prevSubs {
view.isHidden = true
}
let subviews = pages[pageNum].subviews
myqueue.async {
self.isAnimating = true
for view in subviews where self.isAnimating {
self.onMain {
UIView.transition(with: view, duration: 0.3, options: .transitionCrossDissolve, animations: {
view.isHidden = false
})
}
if !self.isAnimating {
break
}
usleep(200 * 1_000)
}
if self.pageNum == 5 {
self.slideShow()
}
if self.pageNum == 6 {
self.slideShow2()
}
self.isAnimating = false
}
}
#objc func previousTapped() {
pageNum -= 1
if isAnimating {
isAnimating = false
}
onMain {
if self.pageNum == 6 {
self.nextBtn.isHidden = false
}
if self.pageNum == 0 {
self.previousBtn.isHidden = true
}
if self.pageNum == 5 {
self.runSlideShow = true
} else {
self.runSlideShow = false
}
if self.pageNum == 6 {
self.runSlideShow2 = true
} else {
self.runSlideShow2 = false
}
self.pageLabel.text = "Page \(self.pageNum + 1)"
self.pages[self.pageNum + 1].removeFromSuperview()
self.view.addSubview(self.pages[self.pageNum])
}
let prevSubs = pages[pageNum + 1].subviews
for view in prevSubs {
view.isHidden = true
}
let subviews = pages[pageNum].subviews
myqueue.async {
self.isAnimating = true
for view in subviews where self.isAnimating {
self.onMain {
UIView.transition(with: view, duration: 0.3, options: .transitionCrossDissolve, animations: {
view.isHidden = false
})
}
if !self.isAnimating {
break
}
usleep(200 * 1_000)
}
if self.pageNum == 5 {
self.slideShow()
}
if self.pageNum == 6 {
self.slideShow2()
}
self.isAnimating = false
}
}
public override func loadView() {
let view = UIView()
view.backgroundColor = .white
view.bounds.size.height = 770
view.bounds.size.width = 450
self.view = view
}
public override func viewDidLoad() {
super.viewDidLoad()
previousBtn = UIButton(frame: CGRect(x: 20, y: 680, width: 100, height: 30))
previousBtn.setImage(#imageLiteral(resourceName: "arrow_left.png"), for: .normal)
previousBtn.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
previousBtn.addTarget(self, action: #selector(previousTapped), for: .touchUpInside)
previousBtn.isHidden = true
nextBtn = UIButton(frame: CGRect(x: 360, y: 680, width: 80, height: 30))
nextBtn.setImage(#imageLiteral(resourceName: "arrow_right.png"), for: .normal)
nextBtn.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
nextBtn.addTarget(self, action: #selector(nextTapped), for: .touchUpInside)
pageLabel = UILabel(frame: CGRect(x: 200, y: 680, width: 100, height: 30))
pageLabel.text = "Page \(pageNum + 1)"
pages = [firstView, secondView, thirdView, fourthView, fifthView, sixthView, seventhView, eigthView]
pageLabel.font = UIFont.systemFont(ofSize: 18, weight: .medium)
view.addSubview(pages[0])
view.addSubview(pageLabel)
view.addSubview(previousBtn)
view.addSubview(nextBtn)
}
}
There can be two approach to this:
rebuild all of your line
shortcut to cleaning is this one:
shift+command+K
as you said you renamed the file.other thing you can do is copy past all code into new file with your requried name.
this should work if your code is good else please do share the code.

Add UIStackView as a customview of a UIBarButtonItem

I try to add a UIStackView as a custom view of a UIBarButtonItem.
I first tried adding a UIView as the custom view.
let list = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 44))
list.backgroundColor = .green
list.addSubview(stackView)
let item = UIBarButtonItem(customView: list )
topViewController?.setToolbarItems([item], animated: true)
This works. I get a green bar in the UIToolBar. Then I tried adding a UIStackView to the UIView.
let red = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 30))
red.backgroundColor = .red
let stackView = UIStackView(frame: CGRect(origin: CGPoint.zero,
size: CGSize(width: 250, height: 44)))
stackView.distribution = .fillEqually
stackView.axis = .horizontal
stackView.spacing = 5
stackView.alignment = .center
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(red)
let list = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 44))
list.backgroundColor = .green
list.addSubview(stackView)
let item = UIBarButtonItem(customView: list )
topViewController?.setToolbarItems([item], animated: true)
However, when I try this, nothing happens. The UIToolBar seems empty. What am I doing wrong?
In this answer, I have used two UIViews.
You have to give height constraints for two UIViews
red.heightAnchor.constraint(equalToConstant: 30).isActive = true;
green.heightAnchor.constraint(equalToConstant: 30).isActive = true;
You have to comment this line,
//stackView.translatesAutoresizingMaskIntoConstraints = false
Full Code:
self.navigationController?.isToolbarHidden = false
let red = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 30))
red.backgroundColor = .red
let green = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 30))
green.backgroundColor = .green
red.heightAnchor.constraint(equalToConstant: 30).isActive = true;
green.heightAnchor.constraint(equalToConstant: 30).isActive = true;
let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 250, height: 30))
stackView.distribution = .fillEqually
stackView.axis = .horizontal
stackView.spacing = 5
stackView.alignment = .center
//stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(red)
stackView.addArrangedSubview(green)
let list = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 44))
list.backgroundColor = .yellow
list.addSubview(stackView)
let item = UIBarButtonItem(customView: list )
self.setToolbarItems([item], animated: true)
Output:

Add label in center of imageView

I have the two images like in the picture at the end of the question (the image of a list and a red dot). I want to add a label in the center of the red dot. This is my code that doesn't work:
image = UIImageView(image: UIImage(named: "pallino"))
image.frame = CGRect(x: 55, y: self.view.frame.height-60, width: 22, height: 22)
self.view.addSubview(image)
image.layer.cornerRadius = image.frame.width/2
label = UILabel(frame: CGRect(x: self.image.center.x, y: self.image.center.y, width: image.frame.size.width, height: image.frame.size.height))
label.text = "4"
label.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.black
image.addSubview(label)
Can someone tell me were am I wrong?
Problem in this line:
label = UILabel(frame: CGRect(x: self.image.center.x, y: self.image.center.y, width: image.frame.size.width, height: image.frame.size.height))
self.image.center.x - The center point is specified in points in the coordinate system of its superview, it is mean that self.image.center is not center of image
You need frame for label, something like this:
let imageSize = 22
let frame = CGRect(x: 0, y: 0, width: imageSize, height: imageSize)
let label = UILabel(frame: frame)
label.aligment = .center
You can set constraint in your label(centered Horizontally and Vertically). Try with the following code.
let label = UILabel()
label.text = "4"
label.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.black
image.addSubview(label)
label.centerXAnchor.constraint(equalTo: self.image.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: self.image.centerYAnchor).isActive = true
To center the label in UIImageView you can refer to this example which is tested and working solution.
extension UIImageView {
/// Create label programmatically
/// - Returns: UILabel
private func ageSensitiveLabel() -> UILabel {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height))
label.text = "Content"
label.font = .systemFont(ofSize: 5.0)
label.textAlignment = .center
label.numberOfLines = 0
label.minimumScaleFactor = 0.5
label.adjustsFontSizeToFitWidth = true
label.baselineAdjustment = .alignCenters
label.textColor = .white
return label
}
/// Add label as subview to UIImageView
func addAgeSensitiveLabel() {
self.subviews.forEach { view in
DispatchQueue.main.async {
view.removeFromSuperview()
}
}
self.addSubview(ageSensitiveLabel())
}
}
Use it with UIImageView
imageView.addAgeSensitiveLabel()

Clipping borders to subviews

I'm trying to make a contour of two UIViews but by using the border property I can't seem to achieve what I want. I'm getting the image on the left, and I want the one on the right:
Here's my code:
let main = UIView()
main.frame = CGRect(x: 50, y: 50, width: 200, height: 100)
main.backgroundColor = UIColor.clear
self.view.addSubview(main)
let v1 = UIView()
v1.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
v1.backgroundColor = UIColor.blue
main.addSubview(v1)
let v2 = UIView()
v2.frame = CGRect(x: 0, y: 50, width: 150, height: 50)
v2.backgroundColor = UIColor.red
main.addSubview(v2)
main.clipsToBounds = true
main.layer.borderColor = UIColor.black.cgColor
main.layer.borderWidth = 3
You need to create custom shaped border layer like so:
let main = UIView()
main.frame = CGRect(x: 50, y: 50, width: 200, height: 100)
main.backgroundColor = UIColor.clear
self.view.addSubview(main)
let v1 = UIView()
v1.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
v1.backgroundColor = UIColor.blue
main.addSubview(v1)
let v2 = UIView()
v2.frame = CGRect(x: 0, y: 50, width: 150, height: 50)
v2.backgroundColor = UIColor.red
main.addSubview(v2)
// Custom Shape Layer
let maskLayer = CAShapeLayer()
maskLayer.frame = main.bounds
// Custom CGPath
let resultPath = CGMutablePath()
resultPath.addPath(CGPath(rect: v1.frame, transform: nil))
resultPath.addPath(CGPath(rect: v2.frame, transform: nil))
maskLayer.path = resultPath
// Add border
let borderLayer = CAShapeLayer()
borderLayer.path = maskLayer.path
borderLayer.strokeColor = UIColor.black.cgColor
borderLayer.lineWidth = 5
borderLayer.frame = main.bounds
borderLayer.zPosition = -1
main.layer.addSublayer(borderLayer)