Swift how to add background color just around text in a label?
You can use a regex to find anything but white spaces, use a while loop to find its occurrences in a string and use those ranges to change the background color of an attributed string:
Swift 4
let mutable = NSMutableAttributedString(string: interests)
var startIndex = interests.startIndex
while let range = interests.range(of: "\\S+", options: .regularExpression, range: startIndex..<interests.endIndex) {
mutable.addAttribute(.backgroundColor, value: UIColor.cyan, range: NSRange(range, in: interests))
startIndex = range.upperBound
}
label.attributedText = mutable
Note: If you would like to add space around your text you can change your regex to " \\S+ "
and don't forget to add spaces at the begin and at the end of your original interests string.
Add highlight/background to only text using Swift
As far as I have tried its not possible to get what you want simply with attributed text because using:
let attributedText = NSMutableAttributedString(string: "Evangelizing Desing Thinking",
attributes: [
.font: UIFont.systemFont(ofSize: 14),
.backgroundColor: UIColor.gray
]
)
Will add extray gray background at the end of each line. My previous answer was not good neither because it only adds a gray background on each word, not on spaces, and as @Alladinian noticed, ranges can be wrong in some cases.
So here is a hack you can use to achieve what you want. It uses multiple labels but it can be easily improved by putting labels in a custom view. So, in your viewDidLoad
/ CustomView
function add:
// Maximum desired width for your text
let maxLabelWidth: CGFloat = 80
// Font you used
let font = UIFont.systemFont(ofSize: 14)
// Your text
let text = "Eva ngel izing Des ing a Thin king"
// Width of a space character
let spaceWidth = NSString(string: " ").size(withAttributes: [NSAttributedString.Key.font: font]).width
// Width of a row
var currentRowWidth: CGFloat = 0
// Content of a row
var currentRow = ""
// Previous label added (we keep it to add constraint betweeen labels)
var prevLabel: UILabel?
let subStrings = text.split(separator: " ")
for subString in subStrings {
let currentWord = String(subString)
let nsCurrentWord = NSString(string: currentWord)
// Width of the new word
let currentWordWidth = nsCurrentWord.size(withAttributes: [NSAttributedString.Key.font: font]).width
// Width of the row if you add a new word
let currentWidth = currentRow.count == 0 ? currentWordWidth : currentWordWidth + spaceWidth + currentRowWidth
if currentWidth <= maxLabelWidth { // The word can be added in the current row
currentRowWidth = currentWidth
currentRow += currentRow.count == 0 ? currentWord : " " + currentWord
} else { // Its not possible to add a new word in the current row, we create a label with the current row content
prevLabel = generateLabel(with: currentRow,
font: font,
prevLabel: prevLabel)
currentRowWidth = currentWordWidth
currentRow = currentWord
}
}
// Dont forget to add the last row
generateLabel(with: currentRow,
font: font,
prevLabel: prevLabel)
Then you have to create the generateLabel
function:
@discardableResult func generateLabel(with text: String,
font: UIFont,
prevLabel: UILabel?) -> UILabel {
let leftPadding: CGFloat = 50 // Left padding of the label
let topPadding: CGFloat = 100 // Top padding of (first) label
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(label)
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: leftPadding).isActive = true
if let prevLabel = prevLabel {
label.topAnchor.constraint(equalTo: prevLabel.bottomAnchor).isActive = true
} else {
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: topPadding).isActive = true
}
label.font = font
label.text = text
label.backgroundColor = .gray
return label
}
Previous answer:
As Yogesh suggested, you can use attributed string:
// Init label
let label = UILabel(frame: CGRect(x: 50, y: 50, width: 90, height: 120))
self.view.addSubview(label)
label.lineBreakMode = .byTruncatingTail
label.numberOfLines = 0
label.backgroundColor = .white
// Create attributed text
let text = "Evangelizing Desing Thinking"
let attributedText = NSMutableAttributedString(string: text,
attributes: [
.font: UIFont.systemFont(ofSize: 14)
]
)
// Find ranges of each word
let subStrings = text.split(separator: " ")
let ranges = subStrings.map { (subString) -> Range<String.Index> in
guard let range = text.range(of: subString) else {
fatalError("something wrong with substring") // This case should not happen
}
return range
}
// Apply background color for each word
ranges.forEach { (range) in
let nsRange = NSRange(range, in: text)
attributedText.addAttribute(.backgroundColor, value: UIColor.gray, range: nsRange)
}
// Finally set attributed text
label.attributedText = attributedText
How to change the background color of a UILabel with swift
Updated for swift 3:
1] if you want to change the UILabel background color, then used below simple lines of code:
yourLabelName.backgroundColor = UIColor.green
Note:- You can also be used different types of standard colors, UIColor.white, UIColor.red...
2] If you want to change the UILabel text color, then used below simple lines of code:
yourLabelName.textColor = UIColor.red
// Enjoy Coding...!
Swift change label text background color according to plist file
Upvoting the other answer because I didn't notice that you're not doing a comparison in your if's. But also wanted to add that you might want to consider a switch statement here instead of a series of if/else statements. For example your viewDidLoad
could be written as:
override func viewDidLoad() {
super.viewDidLoad()
if let card = card {
navigationItem.title = card.name?.capitalizedString
imageView.image = UIImage(named: card.name!.lowercaseString)
titleLabel.text = card.title?.capitalizedString
//Mode label
modeLabel.text = card.mode?.capitalizedString
// Color the text backgrounds and then resize them later for the cards
//Red
switch card.color ?? "none" { // default to none
case "0": titleLabel.backgroundColor = UIColor.greenColor()
case "1": titleLabel.backgroundColor = UIColor.greenColor()
case "2": titleLabel.backgroundColor = UIColor.yellowColor()
case "3": titleLabel.backgroundColor = UIColor.blueColor()
case "4": titleLabel.backgroundColor = UIColor(red: 238.0, green: 204, blue: 204.0, alpha: 1.0)
case "5": titleLabel.backgroundColor = UIColor(red: 238.0, green: 204.0, blue: 204.0, alpha: 1.0)
case "6": titleLabel.backgroundColor = UIColor(red: 104.0, green: 88.0, blue: 139.0, alpha: 1.0)
default: titleLabel.hidden = false
}
// Label style
// self.titleLabelStyle()
}
}
Change background and label colour of UICollectionView cell when it is selected
Just change in your cell
override var isSelected: Bool{
willSet{
super.isSelected = newValue
self.layer.borderColor = newValue ? UIColor.black.cgColor : #colorLiteral(red: 0.6862131953, green: 0.686313808, blue: 0.6861912012, alpha: 1)
self.lblSubItem.textColor = newValue ? UIColor.black : #colorLiteral(red: 0.6862131953, green: 0.686313808, blue: 0.6861912012, alpha: 1)
}
}
Swift - Attribute string background color on next line
Simple solution: - Just add /n in the line one string - it will solve the issue
let attributedString = NSMutableAttributedString(string: "Line 1 Text\n" ?? "")
let attributesForNonSelectedRow = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold),NSAttributedString.Key.foregroundColor:UIColor(rgb: 0x707070),NSAttributedString.Key.backgroundColor:UIColor(rgb: 0xE5E5E5)]
let myTitle = NSAttributedString(string: "Line 2 Text", attributes: attributesForNonSelectedRow)
attributedString.append(myTitle)
searchTitleLabel.lineBreakMode = .byWordWrapping
searchTitleLabel.numberOfLines = 0
searchTitleLabel.attributedText = attributedString
Solution via Constraints:
Why don't you just try to set the constraints for the label by providing Leading, Top and Height constraints, you can achieve it..
Related Topics
Can't Dismiss Navigation Controller in Swift
Change Push Notifications Programmatically in Swift
Match the Data Type of a Object in Swift
Xcode 6 Ignoring Breakpoints - Swift
iOS Swift Remove Uitableview Cell Separator Space
Collectionview Flowlayout Overlapping When Scrolling Not Working
How to Send Request from iOS (Swift) to Dialogflow V2 API Without Cloud Functions
Swift 2 Cannot Invoke 'Fseventstreamcreate' with an Argument List of Type
Give Thumbnail Image with Uiactivityviewcontroller
Swiftui Card Flip Animation with Two Views, One of Which Is Embedded Within a Stack
Error in Facebook Login, iOS 9, Swift
Replay Kit Not Working iPad iOS11 Bug
How to Make Designable Textfield Code Class in Swift
How to Convert Duration Form Youtube API in Swift
How to Change How a Remote Notification Is Presented Before Presentation