Programmatically create UIView with size based on subviews(labels) - ios

I have a scenario where I'm needed to create an UIView completely programatically. This view is displayed as an overlay over a video feed and it contains 2 UILabels as subviews.
These labels can have varying widths and heights so I don't want to create a fixed frame for the UIView or the labels.
I've done this with programatic constrains without issue, but the problem is that the views are glitching when moving the phone and the framework that I'm using that does the video feed recommends not to use autolayout because of this exact problem.
My current code:
I create the view
func ar(_ arViewController: ARViewController, viewForAnnotation: ARAnnotation) -> ARAnnotationView {
let annotationView = AnnotationView() //*this is the view, inherits from UIView
annotationView.annotation = viewForAnnotation
annotationView.delegate = self
return annotationView
}
And the actual view code
class AnnotationView: ARAnnotationView {
var titleLabel: UILabel?
var distanceLabel: UILabel!
var delegate: AnnotationViewDelegate?
override var annotation: ARAnnotation? {
didSet {
loadUI()
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
setupUI()
}
private func setupUI() {
layer.cornerRadius = 5
layer.masksToBounds = true
backgroundColor = .transparentWhite
}
private func loadUI() {
titleLabel?.removeFromSuperview()
distanceLabel?.removeFromSuperview()
let label = UILabel()
label.font = UIFont(name: "AvenirNext-Medium", size: 16.0) ?? UIFont.systemFont(ofSize: 14)
label.numberOfLines = 2
label.textColor = UIColor.white
self.titleLabel = label
distanceLabel = UILabel()
distanceLabel.textColor = .cbPPGreen
distanceLabel.font = UIFont(name: "AvenirNext-Medium", size: 14.0) ?? UIFont.systemFont(ofSize: 12)
distanceLabel.textAlignment = .center
self.translatesAutoresizingMaskIntoConstraints = false
label.translatesAutoresizingMaskIntoConstraints = false
distanceLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(label)
self.addSubview(distanceLabel)
if self.constraints.isEmpty {
NSLayoutConstraint.activate([
NSLayoutConstraint(item: label, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 5),
NSLayoutConstraint(item: label, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: -5),
NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: distanceLabel, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: distanceLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0),
NSLayoutConstraint(item: distanceLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0),
NSLayoutConstraint(item: distanceLabel, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: distanceLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 15),
])
}
if let annotation = annotation as? BikeStationAR {
titleLabel?.text = annotation.address
distanceLabel?.text = String(format: "%.2f km", annotation.distanceFromUser / 1000)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate?.didTouch(annotationView: self)
}
}
So my problem is now: how can I achieve the same behavior, without using autolayout?
Edit: here is a video of the behavior https://streamable.com/s/4zusq/dvbgnb
Edit 2: The solution is based on Mahgol Fa's answer and using a stack view or vertical positioning in order not to set the frame for the individual labels. So the final implementation is
private func loadUI() {
titleLabel?.removeFromSuperview()
distanceLabel?.removeFromSuperview()
let label = UILabel()
label.font = titleViewFont
label.numberOfLines = 0
label.textColor = UIColor.white
label.textAlignment = .center
self.titleLabel = label
distanceLabel = UILabel()
distanceLabel.textColor = .cbPPGreen
distanceLabel.font = subtitleViewFont
distanceLabel.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
distanceLabel.translatesAutoresizingMaskIntoConstraints = false
if let annotation = annotation as? BikeStationAR {
let title = annotation.address
let subtitle = String(format: "%.2f km", annotation.distanceFromUser / 1000)
let fontAttributeTitle = [NSAttributedString.Key.font: titleViewFont]
let titleSize = title.size(withAttributes: fontAttributeTitle)
let fontAttributeSubtitle = [NSAttributedString.Key.font: subtitleViewFont]
let subtitleSize = annotation.address.size(withAttributes: fontAttributeSubtitle)
titleLabel?.text = title
distanceLabel?.text = subtitle
let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: titleSize.width + 5, height: titleSize.height + subtitleSize.height + 5))
stackView.axis = .vertical
stackView.distribution = .fillProportionally
stackView.alignment = .fill
stackView.addArrangedSubview(titleLabel ?? UIView())
stackView.addArrangedSubview(distanceLabel)
frame = stackView.bounds
addSubview(stackView)
}
}

This way you can get the width of your lablels texts:
let fontAttributes1= [NSAttributedStringKey.font: your declared font in your code]
let size1 = (“your string” as String).size(withAttributes: fontAttributes1)
let fontAttributes2= [NSAttributedStringKey.font: your declared font in your code]
let size2 = (“your string” as String).size(withAttributes: fontAttributes2)
Then :
YourView.frame = CGRect( width: size1.width + size2.width + some spacing , height : ....)

Related

Label and TextView overflows Scroll View horizontally

I have a Scroll View, in which I have a Stack View. In the Stack View I have arranged subviews of either UITextView or UILabel elements.
All is done programmatically, without storyboard.
The Scroll View appears and I can scroll it nicely. But unfortunately it scrolls not only vertically (top to bottom) but also horizontally (to the right, out the screen) which I don't want to (this is the reason I have numberOfLines set on the UILabel too, tried to set equal width to the scroll and stack views as the stack view's left/right attributes are connected to the view).
If it's important, this function is called either in viewDidLoad or upon touching a button later.
scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
let leftConstraintScroll = NSLayoutConstraint(item: scrollView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0)
let rightConstraintScroll = NSLayoutConstraint(item: scrollView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0)
let topConstraintScroll = NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: selectedTabIndicator, attribute: .bottom, multiplier: 1, constant: 10)
let bottomConstraintScroll = NSLayoutConstraint(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: editButton, attribute: .top, multiplier: 1, constant: 0)
view.addConstraints([leftConstraintScroll, rightConstraintScroll, topConstraintScroll, bottomConstraintScroll])
stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 10
stackView.isLayoutMarginsRelativeArrangement = true
stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10)
// Several elements are added like this (UITextView):
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.delegate = self
textView.isScrollEnabled = false
textView.font = UIFont.systemFont(ofSize: 15)
textView.backgroundColor = Constants.COLOR_P
textView.textColor = .black
textView.text = "XXX"
stackView.addArrangedSubview(textView)
// Or UILabel:
var label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.textAlignment = .justified
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 15)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .justified
paragraphStyle.hyphenationFactor = 1.0
paragraphStyle.firstLineHeadIndent = 0
paragraphStyle.headIndent = 15
let hyphenAttribute = [NSAttributedString.Key.paragraphStyle: paragraphStyle]
let attributedString = NSMutableAttributedString(string: "XXXXX", attributes: hyphenAttribute)
label.attributedText = attributedString
stackView.addArrangedSubview(label)
scrollView.addSubview(stackView)
let leftConstraint = NSLayoutConstraint(item: stackView, attribute: .left, relatedBy: .equal, toItem: scrollView, attribute: .left, multiplier: 1, constant: 0)
let rightConstraint = NSLayoutConstraint(item: stackView, attribute: .right, relatedBy: .equal, toItem: scrollView, attribute: .right, multiplier: 1, constant: 0)
let topConstraint = NSLayoutConstraint(item: stackView, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: stackView, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottom, multiplier: 1, constant: 0)
scrollView.addConstraints([leftConstraint, rightConstraint, topConstraint, bottomConstraint, bottomConstraint])
Note: selectedTabIndicator and editButton are above and below the scroll view respectively.
First note: when posting code, post some actual code. Your code refers to scrollView and recipeScrollView which, I assume, are the same scroll view. Also, try to post complete information - your code also refers to selectedTabIndicator and editButton, neither of which have been identified nor described in your question.
Second note: start using more modern constraint syntax. For example:
NSLayoutConstraint.activate([
recipeScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0),
recipeScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0),
recipeScrollView.topAnchor.constraint(equalTo: selectedTabIndicator.bottomAnchor, constant: 10.0),
recipeScrollView.bottomAnchor.constraint(equalTo: editButton.topAnchor, constant: 0.0),
])
is much easier to use (and to read) than:
let leftConstraintScroll = NSLayoutConstraint(item: recipeScrollView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0)
let rightConstraintScroll = NSLayoutConstraint(item: recipeScrollView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0)
let topConstraintScroll = NSLayoutConstraint(item: recipeScrollView, attribute: .top, relatedBy: .equal, toItem: selectedTabIndicator, attribute: .bottom, multiplier: 1, constant: 10)
let bottomConstraintScroll = NSLayoutConstraint(item: recipeScrollView, attribute: .bottom, relatedBy: .equal, toItem: editButton, attribute: .top, multiplier: 1, constant: 0)
view.addConstraints([leftConstraintScroll, rightConstraintScroll, topConstraintScroll, bottomConstraintScroll])
Third note: respect the Safe Area... so your leading constraint should be:
recipeScrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 0.0)
and so on.
Fourth note: constrain your scroll view's content to the .contentLayoutGuide, not to the scroll view itself.
To solve your "horizontal scrolling" issue, instead of setting the label and textView widths, set the width of the stack view relative to the scroll view's .frameLayoutGuide:
stackView.widthAnchor.constraint(equalTo: recipeScrollView.frameLayoutGuide.widthAnchor, constant: 0.0)
Here is your code, edited with those tips. I put a blue view near the top to be the selectedTabIndicator and a blue button near the bottom to be the editButton:
class AnotherScrollViewController: UIViewController, UITextViewDelegate {
var recipeScrollView: UIScrollView!
var stackView: UIStackView!
var textView: UITextView!
var selectedTabIndicator: UIView!
var editButton: UIButton!
var editButtonBottom: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
selectedTabIndicator = UIView()
selectedTabIndicator.backgroundColor = .blue
selectedTabIndicator.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(selectedTabIndicator)
editButton = UIButton()
editButton.backgroundColor = .blue
editButton.setTitle("Edit", for: [])
editButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(editButton)
recipeScrollView = UIScrollView()
recipeScrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(recipeScrollView)
let g = view.safeAreaLayoutGuide
editButtonBottom = editButton.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -4.0)
NSLayoutConstraint.activate([
selectedTabIndicator.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
selectedTabIndicator.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 8.0),
selectedTabIndicator.widthAnchor.constraint(equalToConstant: 200.0),
selectedTabIndicator.heightAnchor.constraint(equalToConstant: 4.0),
//editButton.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 4.0),
editButtonBottom,
editButton.centerXAnchor.constraint(equalTo: g.centerXAnchor),
recipeScrollView.topAnchor.constraint(equalTo: selectedTabIndicator.bottomAnchor, constant: 10.0),
recipeScrollView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
recipeScrollView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
recipeScrollView.bottomAnchor.constraint(equalTo: editButton.topAnchor, constant: 0.0),
])
stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 10
stackView.isLayoutMarginsRelativeArrangement = true
stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10)
// Several elements are added like this (UITextView):
textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.delegate = self
textView.isScrollEnabled = false
textView.font = UIFont.systemFont(ofSize: 15)
textView.backgroundColor = .cyan // Constants.COLOR_P
textView.textColor = .black
textView.text = "XXX"
stackView.addArrangedSubview(textView)
// Or UILabel:
var label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.textAlignment = .justified
label.backgroundColor = .green // so we can easily see the label frame
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 15)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .justified
paragraphStyle.hyphenationFactor = 1.0
paragraphStyle.firstLineHeadIndent = 0
paragraphStyle.headIndent = 15
let hyphenAttribute = [NSAttributedString.Key.paragraphStyle: paragraphStyle]
let labelString = "This is the string for the label. It will wrap if it is too long to fit in the allocated width."
//let attributedString = NSMutableAttributedString(string: "XXXXX", attributes: hyphenAttribute)
let attributedString = NSMutableAttributedString(string: labelString, attributes: hyphenAttribute)
label.attributedText = attributedString
stackView.addArrangedSubview(label)
recipeScrollView.addSubview(stackView)
let contentG = recipeScrollView.contentLayoutGuide
let frameG = recipeScrollView.frameLayoutGuide
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: contentG.topAnchor, constant: 0.0),
stackView.leadingAnchor.constraint(equalTo: contentG.leadingAnchor, constant: 0.0),
stackView.trailingAnchor.constraint(equalTo: contentG.trailingAnchor, constant: 0.0),
stackView.bottomAnchor.constraint(equalTo: contentG.bottomAnchor, constant: 0.0),
stackView.widthAnchor.constraint(equalTo: frameG.widthAnchor, constant: 0.0),
])
recipeScrollView.backgroundColor = .red
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
editButton.addTarget(self, action: #selector(self.editButtonTapped), for: .touchUpInside)
}
#objc func editButtonTapped() -> Void {
if textView.isFirstResponder {
textView.resignFirstResponder()
} else {
textView.becomeFirstResponder()
}
}
#objc func adjustForKeyboard(notification: Notification) {
guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardScreenEndFrame = keyboardValue.cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
print(keyboardViewEndFrame.height)
var c: CGFloat = -4.0
if notification.name != UIResponder.keyboardWillHideNotification {
c -= (keyboardViewEndFrame.height - view.safeAreaInsets.bottom)
}
editButtonBottom.constant = c
editButton.setTitle(c == -4 ? "Edit" : "Done", for: [])
}
}
I could solve it, maybe not the best solution, so I leave the question still open for a while, for better solutions.
Basically, I provided a widthAnchor constraint to each UILabel and UITextView when I created them, before adding them to the stack view.
label.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width - 20).isActive = true

Customize UISearchBar in Swift 4

I need to delete the background of the search bar.
The part where text is entered (white color) make it higher.
put a green border around the white part.
customize the font.
I need this:
What I have achieved is this:
My code:
#IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.layer.borderColor = #colorLiteral(red: 0.2352941176, green: 0.7254901961, blue: 0.3921568627, alpha: 1)
self.searchBar.layer.borderWidth = 1
self.searchBar.clipsToBounds = true
self.searchBar.layer.cornerRadius = 20
}
Try using this code:
class JSSearchView : UIView {
var searchBar : UISearchBar!
override func awakeFromNib()
{
// the actual search barw
self.searchBar = UISearchBar(frame: self.frame)
self.searchBar.clipsToBounds = true
// the smaller the number in relation to the view, the more subtle
// the rounding -- https://www.hackingwithswift.com/example-code/calayer/how-to-round-the-corners-of-a-uiview
self.searchBar.layer.cornerRadius = 5
self.addSubview(self.searchBar)
self.searchBar.translatesAutoresizingMaskIntoConstraints = false
let leadingConstraint = NSLayoutConstraint(item: self.searchBar, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 20)
let trailingConstraint = NSLayoutConstraint(item: self.searchBar, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -20)
let yConstraint = NSLayoutConstraint(item: self.searchBar, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
self.addConstraints([yConstraint, leadingConstraint, trailingConstraint])
self.searchBar.backgroundColor = UIColor.clear
self.searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
self.searchBar.tintColor = UIColor.clear
self.searchBar.isTranslucent = true
// https://stackoverflow.com/questions/21191801/how-to-add-a-1-pixel-gray-border-around-a-uisearchbar-textfield/21192270
for s in self.searchBar.subviews[0].subviews {
if s is UITextField {
s.layer.borderWidth = 1.0
s.layer.cornerRadius = 10
s.layer.borderColor = UIColor.green.cgColor
}
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
// the half height green background you wanted...
let topRect = CGRect(origin: .zero, size: CGSize(width: self.frame.size.width, height: (self.frame.height / 2)))
UIColor.green.set()
UIRectFill(topRect)
}
}
And to use it, drop a custom view into your xib or storyboard file and simply set the custom class type to the name of the class (JSSearchView).

Add UIImageView, UILabel to UIStackView programmatically in Swift 4

I'm trying to create a set of UIImageView, UILabel and add to UIStackView programmatically like so.
var someLetters: [Int: String] = [0:"g",1:"n",2:"d"]
let stackView1 = UIStackView(arrangedSubviews: createLetters(someLetters))
someScrollView.addSubview(stackView1)
func createLetters(_ named: [Int: String]) -> [UIView] {
return named.map { name in
let letterImage = UIImageView()
letterImage.image = UIImage(named: "\(name.key)")
let letterLabel = UILabel()
letterLabel.text = name.value
let subView = UIView()
subView.addSubview(letterLabel)
subView.addSubview(letterImage)
return subView
}
}
UIStackViews arrangedSubviews only accepts UIView as a parameter
so I created an additional UIView as a container of UILabel and UIImageView. No compile error but not seeing any UI elements on a screen.
What am I doing wrong here?
Add some constraints to
stackView1.alignment = .center
stackView1.distribution = .fillEqually
stackView1.axis = .vertical
stackView1.spacing = 10.0
stackView1.translatesAutoresizingMaskIntoConstraints = false
let leading = NSLayoutConstraint(item: stackView1, attribute: .leading, relatedBy: .equal, toItem: someScrollView, attribute: .leading, multiplier: 1, constant: 5)
let trailing = NSLayoutConstraint(item: stackView1, attribute: .trailing, relatedBy: .equal, toItem: someScrollView, attribute: .trailing, multiplier: 1, constant: 5)
let height = NSLayoutConstraint(item: stackView1, attribute: .height, relatedBy: .equal, toItem: someScrollView, attribute: .height, multiplier: 0.8, constant: 50)
let alignInCenter = NSLayoutConstraint(item: stackView1, attribute: .centerX, relatedBy: .equal, toItem: someScrollView, attribute: .centerX, multiplier: 1, constant: 1)
let alignInCenterY = NSLayoutConstraint(item: stackView1, attribute: .centerY, relatedBy: .equal, toItem: someScrollView, attribute: .centerY, multiplier: 1, constant: 1)
someScrollView.addSubview(stackView1)
NSLayoutConstraint.activate([alignInCenter,alignInCenterY,leading, trailing, height])
and also add some constraints to letters and ImageView
func createLetters(_ named: [Int: String]) -> [UIView] {
return named.map { name in
let letterImage = UIImageView()
letterImage.image = UIImage(named: "\(name.key)")
letterImage.backgroundColor = UIColor.gray
let letterLabel = UILabel()
letterLabel.text = name.value
letterLabel.backgroundColor = UIColor.green
let stackView = UIStackView(arrangedSubviews: [letterLabel, letterImage])
stackView.alignment = .center
stackView.distribution = .fillEqually
stackView.axis = .horizontal
let widht = NSLayoutConstraint(item: letterImage, attribute: NSLayoutAttribute.width, relatedBy: .equal, toItem: stackView, attribute: .width, multiplier: 1, constant: 100)
let height = NSLayoutConstraint(item: letterImage, attribute: NSLayoutAttribute.height, relatedBy: .equal, toItem: stackView, attribute: .height, multiplier: 1, constant: 100)
NSLayoutConstraint.activate([widht, height])
return stackView
}
}
But I am not sure what axis and what kind of distribution you are looking for in stackView. This code has some of the constraints missing so you have to identify and add them so there is no ambiguity in layouts
As a starting point, try adding the UILabels and UIImageViews to stack views in a storyboard. Here you can see I'm using horizontal stack views contained in a vertical stack view. From here you can see the constraints you'll need to use to create the same in code.
Update code as:
func createLetters(_ named: [Int: String]) -> [UIView] {
return named.map { name in
let letterImage = UIImageView(frame: CGRect(x: 0, y: name.key*10, width: 20, height: 20))
letterImage.image = UIImage(named: "(name.key)")
letterImage.backgroundColor = .green
let letterLabel = UILabel(frame: CGRect(x: 30, y: name.key*10, width: 20, height: 20))
letterLabel.text = name.value
letterLabel.backgroundColor = .red
let stackView = UIStackView(frame: CGRect(x: 0, y:name.key*30, width: 100, height: 50))
stackView.axis = UILayoutConstraintAxis.vertical
stackView.distribution = UIStackViewDistribution.equalSpacing
stackView.alignment = UIStackViewAlignment.center
stackView.spacing = 16.0
stackView.addArrangedSubview(letterImage)
stackView.addArrangedSubview(letterLabel)
return stackView
}
}
This will return 3 stack views as someLetters array count is 3. call it as
self.tview.addSubview(createLetters(someLetters)[0])
self.tview.addSubview(createLetters(someLetters)[1])
self.tview.addSubview(createLetters(someLetters)[2])
if you to get only one stack view label and image with same code then pass only one parameter.

Line before and after text in UILabel

I would like to achieve the same result as this :
I already saw this : Draw line in UILabel before and after text , but I would like to know if there's a way to do this with only one UILabel ?
This is custom view as you requested
import UIKit
class CustomizedUILabel: UIView
{
let label = UILabel()
var lineInsideOffset: CGFloat = 20
var lineOutsideOffset: CGFloat = 4
var lineHeight: CGFloat = 1
var lineColor = UIColor.grayColor()
//MARK: - init
override init(frame: CGRect)
{
super.init(frame: frame)
initLabel()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initLabel()
}
convenience init() {self.init(frame: CGRect.zero)}
func initLabel()
{
label.textAlignment = .Center
label.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: label, attribute: .Top, multiplier: 1, constant: 0)
let bot = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: label, attribute: .Bottom, multiplier: 1, constant: 0)
let lead = NSLayoutConstraint(item: self, attribute: .Leading, relatedBy: .LessThanOrEqual, toItem: label, attribute: .Leading, multiplier: 1, constant: 0)
let trail = NSLayoutConstraint(item: self, attribute: .Trailing, relatedBy: .GreaterThanOrEqual, toItem: label, attribute: .Trailing, multiplier: 1, constant: 0)
let centerX = NSLayoutConstraint(item: self, attribute: .CenterX, relatedBy: .Equal, toItem: label, attribute: .CenterX, multiplier: 1, constant: 0)
addSubview(label)
addConstraints([top, bot, lead, trail, centerX])
//... if the opaque property of your view is set to YES, your drawRect: method must totally fill the specified rectangle with opaque content.
//http://stackoverflow.com/questions/11318987/black-background-when-overriding-drawrect-in-uiscrollview
opaque = false
}
//MARK: - drawing
override func drawRect(rect: CGRect)
{
let lineWidth = label.frame.minX - rect.minX - lineInsideOffset - lineOutsideOffset
if lineWidth <= 0 {return}
let lineLeft = UIBezierPath(rect: CGRectMake(rect.minX + lineOutsideOffset, rect.midY, lineWidth, 1))
let lineRight = UIBezierPath(rect: CGRectMake(label.frame.maxX + lineInsideOffset, rect.midY, lineWidth, 1))
lineLeft.lineWidth = lineHeight
lineColor.set()
lineLeft.stroke()
lineRight.lineWidth = lineHeight
lineColor.set()
lineRight.stroke()
}
}
Usage in code: in usual case you should provide top, leading and trailing/width constraints and let CustomizedUILabel to determine height by its internal UILabel. Lets show our label in debug mode in some view controller's viewDidLoad method:
override func viewDidLoad()
{
super.viewDidLoad()
let customizedLabel = CustomizedUILabel()
customizedLabel.label.text = "RATE YOUR RIDE"
customizedLabel.label.textColor = UIColor.grayColor()
customizedLabel.label.font = customizedLabel.label.font.fontWithSize(25)
customizedLabel.backgroundColor = UIColor.redColor()
view.addSubview(customizedLabel)
customizedLabel.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: customizedLabel, attribute: .Top, multiplier: 1, constant: -100)
let trail = NSLayoutConstraint(item: view, attribute: .Trailing, relatedBy: .Equal, toItem: customizedLabel, attribute: .Trailing, multiplier: 1, constant: 0)
let lead = NSLayoutConstraint(item: view, attribute: .Leading, relatedBy: .Equal, toItem: customizedLabel, attribute: .Leading, multiplier: 1, constant: 0)
view.addConstraints([top, trail, lead])
}
Usage in xib/storyboard: as soon as you implemented init with coder initializer you can use this view in xib/storyboard. You need add UIView element to your superview, assign Class for this element to CustomizedUILabel, perform constraints and make outlet. Then you can use it with pretty same way:
#IBOutlet weak var customizedLabel: CustomizedUILabel!
override func viewDidLoad()
{
super.viewDidLoad()
customizedLabel.label.text = "RATE YOUR RIDE"
customizedLabel.label.textColor = UIColor.grayColor()
customizedLabel.label.font = customizedLabel.label.font.fontWithSize(25)
customizedLabel.backgroundColor = UIColor.redColor()
}
UILabel * label = [UILabel new];
label.frame = CGRectMake(0,0,0,20);
label.text = #"Rate Your Ride";
[self.view addSubview:label];
[label sizeToFit];
float w = self.view.frame.size.width;
float lw = label.frame.size.width;
float offset = (w-lw)/2;
float padding = 20.0f;
//center the label
[label setFrame:CGRectMake(offset, 0, lw, 20)];
//make the borders
UIImageView * left = [UIImageView new];
left.frame = CGRectMake(0, 9, offset-padding, 2);
left.backgroundColor = [UIColor blackColor];
[self.view addSubview:left];
UIImageView * right = [UIImageView new];
right.frame = CGRectMake(w-offset+padding, 9, offset-padding, 2);
right.backgroundColor = [UIColor blackColor];
[self.view right];
OR
make the label background the same colour as its parent and put a single line behind it.

Check for Truncation in UILabel - iOS, Swift

I'm working on an app in swift. Currently, I'm working on the population of a table view with custom cells, see screenshot. However, right now I have the text set so that the title is exactly 2 lines and the summary is exactly 3 lines. By doing this, the text is sometimes truncated. Now, I want to set the priority for text in the title, so that if the title is truncated when it is 2 lines long I expand it to 3 lines and make the summary only 2 lines. I tried doing this with auto layout, but failed. Now I tried the following approach, according to this and this, but the function below also didn't seem to accurately determine if the text is truncated.
func isTruncated(label:UILabel) -> Bool {
let context = NSStringDrawingContext()
let text : NSAttributedString = NSAttributedString(string: label.text!, attributes: [NSFontAttributeName : label.font])
let labelSize : CGSize = CGSize(width: label.frame.width, height: CGFloat.max)
let options : NSStringDrawingOptions = unsafeBitCast(NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue | NSStringDrawingOptions.UsesFontLeading.rawValue, NSStringDrawingOptions.self)
let labelRect : CGRect = text.boundingRectWithSize(labelSize, options: options, context: context)
if Float(labelRect.height/label.font.lineHeight) > Float(label.numberOfLines) {
return true
} else {
return false
}
}
Can anybody help? How can I change my function to make this work? Or should work with different auto layout constraints and how?
Thanks so much!
EDIT:
this is my current code. Some auto layout is done is the storyboard, however the changing auto layout is done in code.
import UIKit
class FeedTableViewCell: UITableViewCell {
var thumbnailImage = UIImageView()
#IBOutlet var titleText: UILabel!
#IBOutlet var summaryText: UILabel!
#IBOutlet var sourceAndDateText: UILabel!
var imgTitleConst = NSLayoutConstraint()
var imgSummaryConst = NSLayoutConstraint()
var imgDetailConst = NSLayoutConstraint()
var titleConst = NSLayoutConstraint()
var summaryConst = NSLayoutConstraint()
var detailConst = NSLayoutConstraint()
var titleHeightConst = NSLayoutConstraint()
var summaryHeightConst = NSLayoutConstraint()
var imageRemoved = false
var titleConstAdd = false
override func awakeFromNib() {
super.awakeFromNib()
thumbnailImage.clipsToBounds = true
summaryText.clipsToBounds = true
titleText.clipsToBounds = true
sourceAndDateText.clipsToBounds = true
addImage()
}
func removeImage() {
if let viewToRemove = self.viewWithTag(123) {
imageRemoved = true
viewToRemove.removeFromSuperview()
self.contentView.removeConstraints([imgTitleConst, imgSummaryConst, imgDetailConst])
titleConst = NSLayoutConstraint(item: self.titleText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 14)
summaryConst = NSLayoutConstraint(item: summaryText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 14)
detailConst = NSLayoutConstraint(item: sourceAndDateText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 14)
self.contentView.addConstraints([titleConst, detailConst, summaryConst])
setNumberOfLines()
self.contentView.layoutSubviews()
}
}
func addImage() {
thumbnailImage.tag = 123
thumbnailImage.image = UIImage(named: "placeholder")
thumbnailImage.frame = CGRectMake(14, 12, 100, 100)
thumbnailImage.contentMode = UIViewContentMode.ScaleAspectFill
thumbnailImage.clipsToBounds = true
self.contentView.addSubview(thumbnailImage)
if imageRemoved {
self.contentView.removeConstraints([titleConst, summaryConst, detailConst])
}
var widthConst = NSLayoutConstraint(item: thumbnailImage, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)
var heightConst = NSLayoutConstraint(item: thumbnailImage, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)
var leftConst = NSLayoutConstraint(item: thumbnailImage, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 14)
var topConst = NSLayoutConstraint(item: thumbnailImage, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 12)
imgTitleConst = NSLayoutConstraint(item: self.titleText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.thumbnailImage, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 8)
imgSummaryConst = NSLayoutConstraint(item: summaryText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.thumbnailImage, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 8)
imgDetailConst = NSLayoutConstraint(item: sourceAndDateText, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.thumbnailImage, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 8)
self.contentView.addConstraints([widthConst, heightConst, leftConst, topConst, imgTitleConst, imgSummaryConst, imgDetailConst])
setNumberOfLines()
self.contentView.layoutSubviews()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setNumberOfLines() {
if titleConstAdd {
self.contentView.removeConstraints([titleHeightConst, summaryHeightConst])
}
if titleText.numberOfLines == 3 {
titleText.numberOfLines = 2
}
if countLabelLines(titleText) > 2 {
titleText.numberOfLines = 3
summaryText.numberOfLines = 2
println("adjusting label heigh to be taller")
titleHeightConst = NSLayoutConstraint(item: titleText, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 51)
summaryHeightConst = NSLayoutConstraint(item: summaryText, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 32)
self.contentView.addConstraints([titleHeightConst, summaryHeightConst])
} else {
titleText.numberOfLines = 2
summaryText.numberOfLines = 3
titleHeightConst = NSLayoutConstraint(item: titleText, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 36)
summaryHeightConst = NSLayoutConstraint(item: summaryText, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 47)
self.contentView.addConstraints([titleHeightConst, summaryHeightConst])
}
titleConstAdd = true
}
}
func countLabelLines(label:UILabel)->Int{
if let text = label.text{
// cast text to NSString so we can use sizeWithAttributes
var myText = text as NSString
//Set attributes
var attributes = [NSFontAttributeName : UIFont.boldSystemFontOfSize(14)]
//Calculate the size of your UILabel by using the systemfont and the paragraph we created before. Edit the font and replace it with yours if you use another
var labelSize = myText.boundingRectWithSize(CGSizeMake(label.bounds.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
//Now we return the amount of lines using the ceil method
var lines = ceil(CGFloat(labelSize.height) / label.font.lineHeight)
println(labelSize.height)
println("\(lines)")
return Int(lines)
}
return 0
}
You can use the sizeWithAttributes method from NSString to get the number of lines your UILabel has. You will have to cast your label text to NSString first to use this method:
func countLabelLines(label:UILabel)->Int{
if let text = label.text{
// cast text to NSString so we can use sizeWithAttributes
var myText = text as NSString
//A Paragraph that we use to set the lineBreakMode.
var paragraph = NSMutableParagraphStyle()
//Set the lineBreakMode to wordWrapping
paragraph.lineBreakMode = NSLineBreakMode.ByWordWrapping
//Calculate the size of your UILabel by using the systemfont and the paragraph we created before. Edit the font and replace it with yours if you use another
var labelSize = myText.sizeWithAttributes([NSFontAttributeName : UIFont.systemFontOfSize(17), NSParagraphStyleAttributeName : paragraph.copy()])
//Now we return the amount of lines using the ceil method
var lines = ceil(CGFloat(size.height) / label.font.lineHeight)
return Int(lines)
}
return 0
}
Edit
If this method doesn't work for you because your label hasn't a fixed width, you can use boundingRectWithSize to get the size of the label and use that with the ceil method.
func countLabelLines(label:UILabel)->Int{
if let text = label.text{
// cast text to NSString so we can use sizeWithAttributes
var myText = text as NSString
//Set attributes
var attributes = [NSFontAttributeName : UIFont.systemFontOfSize(UIFont.systemFontSize())]
//Calculate the size of your UILabel by using the systemfont and the paragraph we created before. Edit the font and replace it with yours if you use another
var labelSize = myText.boundingRectWithSize(CGSizeMake(label.bounds.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
//Now we return the amount of lines using the ceil method
var lines = ceil(CGFloat(labelSize.height) / label.font.lineHeight)
return Int(lines)
}
return 0
}
Swift 3
A simple solution is counting the number of lines after assigning the string and compare to the max number of lines of the label.
import Foundation
import UIKit
extension UILabel {
func countLabelLines() -> Int {
// Call self.layoutIfNeeded() if your view is uses auto layout
let myText = self.text! as NSString
let attributes = [NSFontAttributeName : self.font]
let labelSize = myText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil)
return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
}
func isTruncated() -> Bool {
if (self.countLabelLines() > self.numberOfLines) {
return true
}
return false
}
}
This works for labels with fixed width and fixed number of lines or fixed height:
extension UILabel {
func willBeTruncated() -> Bool {
let label:UILabel = UILabel(frame: CGRectMake(0, 0, self.bounds.width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = self.font
label.text = self.text
label.sizeToFit()
if label.frame.height > self.frame.height {
return true
}
return false
}
}

Resources