UILabel is not visible on dynamically created UIView - ios

I'm attempting to create a custom view programmatically to show an error message for an error condition. The following is what the ViewController looks like:
// init
var titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.lineSpacing = 40.0
titleParagraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping
let titleString = NSMutableAttributedString(
string: "Oops! Error.",
attributes: [ // Some attributes
]
)
var errorView = UIView()
errorView.frame = self.view.bounds
errorView.backgroundColor = UIColor.redColor()
var errorLabel = UILabel()
errorLabel.textAlignment = .Center
errorLabel.attributedText = titleString
errorLabel.lineBreakMode = .ByWordWrapping
errorLabel.backgroundColor = UIColor.blueColor()
errorLabel.textColor = UIColor.greenColor()
errorView.addSubview(errorLabel)
self.errorView = errorView
// usage
if(errorCondition) {
self.view = self.errorView
}
I can only see a red coloured rectangle, which means that only the errorView is visible. What am I doing wrong?

I think your UILabel needs a frame.

Related

Set subviews to correct dimensions after parent view has scaled

I am creating a UIView programtically that is scaled and translated to the center of my view. I am then adding subviews (UILabel's) to that view programatically and the issue I have encountered is that the text for the UILabel's is stretched and difficult to read. I have tried to set autoresizeSubviews = false however this did not have any effect. I have also tried setting the number of lines but this did not have any affect either. I wanted to know if there was a possible solution to this problem that perhaps I am overlooking. Below is my code...
Here i instantiate each UI object to be used on view including view itself
//create lazy vars for UIView that is instantiated until it is initialized
lazy var enlargedView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 12.0
view.clipsToBounds = true
return view
}()
lazy var profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.frame = CGRect(x: self.enlargedView.center.x, y: self.enlargedView.bounds.origin.y + 20.0, width: self.enlargedView.bounds.width * 0.4, height: self.enlargedView.bounds.width * 0.4)
imageView.layer.cornerRadius = imageView.frame.width / 2
imageView.clipsToBounds = true
imageView.layer.borderColor = UIColor.black.cgColor
imageView.layer.borderWidth = 1.0
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
lazy var usernameLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textColor = UIColor.black
let font = UIFont(name: Constants.Fonts.GILL_SANS_SEMIBOLD, size: 8.0)
let fontMetrics = UIFontMetrics(forTextStyle: .body)
label.font = fontMetrics.scaledFont(for: font!)
label.textAlignment = .center
//label.sizeToFit()
label.translatesAutoresizingMaskIntoConstraints = false
return label
} ()
lazy var userDataLabel: UILabel = {
let label = UILabel()
//creates implicit height for label
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textColor = UIColor.black
let font = UIFont(name: Constants.Fonts.GILL_SANS, size: 10.0)
let fontMetrics = UIFontMetrics(forTextStyle: .body)
label.font = fontMetrics.scaledFont(for: font!)
label.textAlignment = .center
label.sizeToFit()
label.translatesAutoresizingMaskIntoConstraints = false
return label
} ()
Next I create animation for view to scale and translate once a collectionView cell is tapped
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchCell", for: indexPath) as! SearchCell
let currentFrame = cell.frame
let selectedUser = userNameArr[indexPath.row]
enlargedView.frame = currentFrame
let backgroundView = UIView(frame: self.view.bounds)
backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: {
self.view.addSubview(self.enlargedView)
//translate view to center of screen
self.enlargedView.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
//while view is being translated background subview should be inserted
self.view.insertSubview(backgroundView, belowSubview: self.enlargedView)
self.enlargedView.transform = CGAffineTransform(scaleX: 2.5, y: 2.5)
}) { (viewWasEnlarged) in
if viewWasEnlarged {
if let profile = selectedUser.user_photo_url {
self.profileImageView.kf.setImage(with: URL(string:Constants.Server.MEDIA_URL + profile))
} else {
self.profileImageView.image = UIImage(named: "user_icon")
}
self.enlargedView.addSubview(self.profileImageView)
self.profileImageView.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalTo(self.enlargedView.snp.top).offset(20.0)
make.width.equalTo(self.enlargedView.snp.width).multipliedBy(0.4)
make.height.equalTo(self.enlargedView.snp.width).multipliedBy(0.4)
}
//USERNAME label
self.usernameLabel.text = selectedUser.user_name!
self.enlargedView.addSubview(self.usernameLabel)
self.usernameLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.width.equalTo(self.enlargedView.snp.width).multipliedBy(0.9)
make.top.equalTo(self.profileImageView.snp.bottom).offset(5.0)
}
//reset enlarged view back to original value
self.usernameLabel.transform = CGAffineTransform.identity
//USER DATA label
var userAge = ""
var userRelationshipStatus = ""
if let userYear = selectedUser.user_birthday {
let yr = self.calendar.dateComponents([.year], from: userYear).year
userAge = "\(yr!)"
}
if let status = selectedUser.user_stats {
userRelationshipStatus = status
}
self.userDataLabel.text = userAge + " | " + userRelationshipStatus
self.enlargedView.addSubview(self.userDataLabel)
self.userDataLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.width.equalTo(self.enlargedView.snp.width).multipliedBy(0.2)
make.top.equalTo(self.usernameLabel.snp.bottom).offset(3.0)
}
//create label to show HUB as well
//create bio
//show Path??
}
}
The imageView is unaffected however the text itself is not reflected correctly

How to customize the searchBar in a UISearchController?

I know how to set the appearance for a independent UISearchBar, just like the following.
let searchField = searchBar.value(forKey: "searchField") as? UITextField
if let field = searchField {
field.backgroundColor = UIColor.defaultBackgroundColor
field.layer.cornerRadius = 15.0
field.textColor = .white
field.tintColor = .white
field.font = UIFont.systemFont(ofSize: fl(13))
field.layer.masksToBounds = true
field.returnKeyType = .search
}
But this is not working in the UISearchController.
I want to set the text color of the placeholder and the left magnifying lens icon to pure white.
(It seems there is a colored layer over them now).
In addition, the input text is black now, I want it to be white too.
In a conclusion, I want to modify the following properties.
1. textField background color
2. textFiled placeholder text color
3. textFiled text color
4. textFiled font
Anyone know how do it?
Add the following with your code in viewDidAppear:
let placeholderString = NSAttributedString(string: "Placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
field.attributedPlaceholder = placeholderString
let iconView = field.leftView as! UIImageView
iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate)
iconView.tintColor = .white
Updata:
Put those settings in ViewDidAppear() did solve a part of my problem.
But the textfield's background color changed when I set the bar's background color.
Because searchBar.barTintColor = .red is not working in iOS11's UISearchController embedded in navigation item, I used searchBar.backgroundColor = .red
It confused me a lot.
So how to change searchBar's background and textField's background separately?
set attributedPlaceholder for textfield of search bar
#IBOutlet weak var sbSearchBar: UISearchBar!
if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField {
textfield.backgroundColor = UIColor.red
textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
if let leftView = textfield.leftView as? UIImageView {
leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
leftView.tintColor = UIColor.white
}
}
Here is result:
Update:
I think, this may help you: how to change uitextfield color in searchcontroller?
Just apply your color combination in this code and see.
if #available(iOS 11.0, *) {
let sc = UISearchController(searchResultsController: nil)
sc.delegate = self
let scb = sc.searchBar
scb.tintColor = UIColor.white
scb.barTintColor = UIColor.white
if let textfield = scb.value(forKey: "searchField") as? UITextField {
//textfield.textColor = // Set text color
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.white
// Rounded corner
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;
}
}
if let navigationbar = self.navigationController?.navigationBar {
navigationbar.barTintColor = UIColor.blue
}
navigationItem.searchController = sc
navigationItem.hidesSearchBarWhenScrolling = false
}
Result:
Add the following with your code in viewDidAppear:
let placeholderString = NSAttributedString(string: "Placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
field.attributedPlaceholder = placeholderString
let iconView = field.leftView as! UIImageView
iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate)
iconView.tintColor = .white
Update - the following is the complete code to customize UISearchController colors:
override func viewDidAppear(_ animated: Bool) {
//sets navigationbar backgroundColor
if let navigationbar = self.navigationController?.navigationBar {
navigationbar.barTintColor = UIColor.magenta
}
let searchField = searchController.searchBar.value(forKey: "searchField") as? UITextField
//sets searchBar backgroundColor
searchController.searchBar.backgroundColor = .blue
if let field = searchField {
field.layer.cornerRadius = 15.0
//sets text Color
field.textColor = .brown
//sets indicator and cancel button Color
field.tintColor = .green
field.font = UIFont.systemFont(ofSize: 13)
field.layer.masksToBounds = true
field.returnKeyType = .search
//sets placeholder text Color
let placeholderString = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
field.attributedPlaceholder = placeholderString
//sets icon Color
let iconView = field.leftView as! UIImageView
iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate)
iconView.tintColor = .cyan
//sets textField backgroundColor
if let backgroundview = field.subviews.first {
backgroundview.backgroundColor = UIColor.yellow
}
}
}
The accepted solution does not work for iOS 13, you are getting the following error (testet with Obj-C Code):
Terminating app due to uncaught exception 'NSGenericException',
reason: 'Access to UISearchBar's _searchField ivar is prohibited. This
is an application bug'
But now you have the option to access UISearchBar's TextField directly, without using a private API.
if (#available(iOS 13, *)) {
self.searchController.searchBar.searchTextField.backgroundColor = [UIColor whiteColor];
self.searchController.searchBar.searchTextField.tintColor = [UIColor darkGrayColor];
}
else {
UITextField *txfSearchField = [self.searchController.searchBar valueForKey:#"_searchField"];
UIView *background = txfSearchField.subviews.firstObject;
background.layer.cornerRadius = 10;
background.clipsToBounds = true;
background.backgroundColor=[UIColor whiteColor];
txfSearchField.tintColor=[UIColor darkGrayColor];
txfSearchField.textColor = [UIColor redColor];
}

Swift UIlabels not showing properly in uistackview

I am trying to programatically add uilabels into a stackview but for some reason it is not showing up properly. Here is what I have:
let label = UILabel()
label.textColor = UIColor.black
label.text = "Text that goes before "
let matlabel = MTMathUILabel()
matlabel.labelMode = MTMathUILabelMode.text
matlabel.latex = "$\\frac{x}{y}$"
matlabel.textColor = UIColor.black
let endLabel = UILabel()
label.textColor = UIColor.black
label.text = "? after"
self.textStack.addArrangedSubview(label)
self.textStack.addArrangedSubview(matlabel)
self.textStack.addArrangedSubview(endLabel)
And here is what I get
You create a "endLabel" but you didn't set text on it. You mistakenly set text on "label" so it just override your "label" text. try the following code:
let label = UILabel()
label.textColor = UIColor.black
label.text = "Text that goes before "
let matlabel = MTMathUILabel()
matlabel.labelMode = MTMathUILabelMode.text
matlabel.latex = "$\\frac{x}{y}$"
matlabel.textColor = UIColor.black
let endLabel = UILabel()
endLabel.textColor = UIColor.black
endLabel.text = "? after"
self.textStack.addArrangedSubview(label)
self.textStack.addArrangedSubview(matlabel)
self.textStack.addArrangedSubview(endLabel)
Well, I think what you wanted to really do was:
self.textStack.addArrangedSubview(label)
self.textStack.addArrangedSubview(matlabel)
self.textStack.addArrangedSubview(endLabel)
But, to your point, the "label" is not appearing. Have you tried setting the alignment and distribution?

Multiline Navigationbar Title

I am trying to set the title label in my navigation bar to allow multiple lines. I have custom navigation controller code that I am placing the multiline code into. I know that the code already there works, but my multiline part is not working.
let titleLabel = UILabel()
titleLabel.frame = CGRectMake(0, 0, self.navigationBar.frame.width, self.navigationBar.frame.height * 2)
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .ByWordWrapping
navigationItem.titleView = titleLabel
But the text still runs off at the end. I've also tried putting this into the individual view controller itself, adding self.navigationController?. in front of navigationItem with the same results.
Is there something I'm missing in my code that would keep the title label from using multiple lines?
Here is a code example of how you can create a multiline navigationBar title
let label: UILabel = UILabel(frame: CGRectMake(0, 0, 400, 50))
label.backgroundColor = UIColor.clearColor()
label.numberOfLines = 2
label.font = UIFont.boldSystemFontOfSize(16.0)
label.textAlignment = .Center
label.textColor = UIColor.whiteColor()
label.text = "This is a\nmultiline string for the navBar"
self.navigationItem.titleView = label
Swift 5.x:
let label = UILabel()
label.backgroundColor = .clear
label.numberOfLines = 2
label.font = UIFont.boldSystemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = .white
label.text = "This is a\nmultiline string for the navBar"
self.navigationItem.titleView = label
This is doable in a storyboard. Just drag a UIView into the Navigation bar, then drag a UILabel onto it in the document outline, set lines to 2 and alignment to center.
Use this to get the label position exactly as you want it:
let labelWidth = navBar.bounds.width - 110
let label = UILabel(frame: CGRect(x:(navBar.bounds.width/2) - (labelWidth/2), y:0, width:labelWidth, height:navBar.bounds.height))
label.backgroundColor = UIColor.clear
label.numberOfLines = 0
label.font = UIFont.boldSystemFont(ofSize: 13.0)
label.textAlignment = .center
label.textColor = UIColor.black
label.lineBreakMode = .byWordWrapping
label.text = loadedName
navBar.topItem?.title = nil
navBar.addSubview(label)
the 110 value in the top line is the spacing you want either side of the label.
swift 5+ very easy solution
func titleMultiLine(topText: String, bottomText: String) {
// let titleParameters = [NSForegroundColorAttributeName : UIColor.white,
// NSFontAttributeName : UIFont.<Font>]
// let subtitleParameters = [NSForegroundColorAttributeName : UIColor.<Color>(),
// NSFontAttributeName : UIFont.<Font>]
let titleParameters = [NSAttributedString.Key.foregroundColor : UIColor.white]
let subtitleParameters = [NSAttributedString.Key.foregroundColor : UIColor.white]
let title:NSMutableAttributedString = NSMutableAttributedString(string: topText, attributes: titleParameters)
let subtitle:NSAttributedString = NSAttributedString(string: bottomText, attributes: subtitleParameters)
title.append(NSAttributedString(string: "\n"))
title.append(subtitle)
let size = title.size()
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
titleLabel.attributedText = title
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
navigationItem.titleView = titleLabel
}
Function Calling
self.titleMultiLine(topText: "I am top text Title", bottomText: "bottom text")

UILabel resizes its SuperView?

I have the following view which contains a UILabel:
class MyView : UIView {
func viewDidLoad() {
self.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
bottomView = UIView(frame: CGRectMake(self.bounds.origin.x, self.bounds.origin.y + self.imageView!.bounds.size.width, self.bounds.size.width, self.bounds.size.height - self.imageView!.bounds.size.height))
// bottomView frame calculation is: (0.0, 355.0, 355.0, 130.0)
bottomView?.backgroundColor = UIColor.greenColor()
bottomView?.autoresizingMask = UIViewAutoresizing.FlexibleWidth
bottomView?.clipsToBounds = true
self.addSubview(self.bottomView!)
var descriptionRect: CGRect = CGRectInset(self.bottomView!.bounds, leftRightInset, 20/2)
let descriptionLabel = UILabel()
descriptionLabel.numberOfLines = 3
descriptionLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth
descriptionLabel.font = UIFont(name: MGFont.helvetica, size: 22)
descriptionLabel.textColor = UIColor.whiteColor()
descriptionLabel.textAlignment = NSTextAlignment.Left
descriptionLabel.backgroundColor = UIColor.blueColor()
var paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail
let attributes = [NSParagraphStyleAttributeName : paragraphStyle]
descriptionLabel.attributedText = NSAttributedString(string: previewCard.title, attributes:attributes)
bottomView?.addSubview(descriptionLabel)
descriptionLabel.bounds = descriptionRect
descriptionLabel.sizeToFit()
descriptionLabel.center = CGPointMake(bottomView!.bounds.width/2, bottomView!.bounds.height/2 - hotelNameLableHeight/2)
}
}
The height of the bottomView should always be fixed.
MyView is resized during runtime. This means that the green bottom view also increases in size.
Here is the result when the label has two and three lines:
It appears that the UILabel resizes its super view.
Note that I do not use AutoLayout.
override func layoutSubviews() {
super.layoutSubviews()
}
How can I prevent the UILabel from resizing its SuperView?
Edit: I also tried to comment bottomView?.clipsToBounds = true
Override setFrame: and setBounds: of the super view (subclass if they're plain UIViews), add breakpoints, and see the stack trace to find out what's causing them to resize.
There is no need to set the autoResizingMask on the label, just set the frame and it will get automatically centered. And of course you can set the insets for the UILabel accordingly. I've add below testing code FYI:
override func viewDidLayoutSubviews() {
addTestView(CGRectMake(0, 200, view.bounds.width, 50), labelStr: "I am a short testing label")
addTestView(CGRectMake(0, 260, view.bounds.width, 50), labelStr: "I am a very longlonglonglonglonglonglong testing label")
addTestView(CGRectMake(0, 320, view.bounds.width, 50), labelStr: "I am a very longlonglonglonglonglonglonglonglonglonglonglong testing label. Will be truncated")
}
func addTestView(frame:CGRect, labelStr: String){
let bottomView = UIView(frame:frame)
bottomView.backgroundColor = UIColor.greenColor()
bottomView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
bottomView.clipsToBounds = true
view.addSubview(bottomView)
var label = UILabel(frame: bottomView.bounds)
label.textAlignment = NSTextAlignment.Left
label.numberOfLines = 0
label.text = labelStr
bottomView.addSubview(label)
}

Resources