9 Notes for me in April Swift 4.2
1. if you found an error like "Use of undeclared type 'UIColor' "
error Use of undeclared type 'UIColor', or Use of undeclared type 'UICgrect' all about 'UI'
a solution is : maybe you forgot "import UIKit"
2. Set logo Uiimage in Navigation item title
this example code for set navigation item change from title to image / your logo
//------------------------------------------------------------------------
func setUpNavigationBarTitleImage() {
let navController = navigationController!
let image = UIImage(named: "logo.png")!
let imageView = UIImageView(image: image)
let bannerWidth = navController.navigationBar.frame.size.width
let bannerHeight = navController.navigationBar.frame.size.height
imageView.frame = CGRect(x: 0, y: 0, width: bannerWidth, height: bannerHeight)
imageView.contentMode = .scaleAspectFit
imageView.center = navController.navigationBar.center
navigationItem.titleView = imageView
}
//------------------------------------------------------------------------
and then set in viewdidload.
//------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
setUpNavigationBarTitleImage()
}
//------------------------------------------------------------------------
3. function " handler: " in UIAlertController must you know
handler as parameter, you can use like an example below
//------------------------------------------------------------------------
let ac = UIAlertController(title: "Open page…", message: nil, preferredStyle: .actionSheet)
ac.addAction(UIAlertAction(title: "apple.com", style: .default, handler: openPage))
....
func openPage(action: UIAlertAction) {
let url = URL(string: "https://" + action.title!)!
webView.load(URLRequest(url: url))
}
//------------------------------------------------------------------------
This method takes one parameter, which is the UIAlertAction object that was selected by the user. Obviously, it won't be called if Cancel was tapped, because that had a nil handler rather than openPage.
4. Remove separator last line use viewForFooterInSection
tableview just remove separator last line or last index
//------------------------------------------------------------------------
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView(frame: .zero)
}
//------------------------------------------------------------------------
https://stackoverflow.com/questions/44223810/last-static-cell-separator-line-appears-after-reloading-table-view
5. Height tableview dynamic by indexPath row
Is there any way by which I can get row height of each row in a UITableView. I have a UITableView which contains data which is dynamic, u can use in numberOfRowsInSection for dynamic and static use in viewdidload.
heightManual.constant = tableView.contentSize.height
6. How add separator to string at every 3 characters in swift?
ex:
let char = "5551190003451"
let account = char.inserting(separator: "-", every: 3)
print(account) // Result -> "555-119-000-345-1"
//------------------------------------------------------------------------
link : https://stackoverflow.com/a/34454633/8366535
7. String Attribute Swift 4.2
link : https://stackoverflow.com/a/32269975/8366535
8. Int To Date
Link: https://stackoverflow.com/questions/39934057/convert-date-to-integer-in-swift
Link: https://blog.apoorvmote.com/convert-date-to-string-vice-versa-in-swift/
Check Int to Date : https://www.epochconverter.com/
Date Helper: https://github.com/mikaelbo/AFDateHelper
OR use this func:
Swift Remove character from string, example:
//------------------------------------------------------------------------
let str = "<b>loream ipsum</b> dolor"
print(removeStrChar(str)) // loream ipsum dolor
func removeStrChar(_ str: String) -> String {
let removeStr = str.replace(string: "<b>", replacement: "")
let removeStr2 = removeStr.replace(string: "</b>", replacement: "")
return removeStr2
}
//------------------------------------------------------------------------
error Use of undeclared type 'UIColor', or Use of undeclared type 'UICgrect' all about 'UI'
a solution is : maybe you forgot "import UIKit"
2. Set logo Uiimage in Navigation item title
this example code for set navigation item change from title to image / your logo
//------------------------------------------------------------------------
func setUpNavigationBarTitleImage() {
let navController = navigationController!
let image = UIImage(named: "logo.png")!
let imageView = UIImageView(image: image)
let bannerWidth = navController.navigationBar.frame.size.width
let bannerHeight = navController.navigationBar.frame.size.height
imageView.frame = CGRect(x: 0, y: 0, width: bannerWidth, height: bannerHeight)
imageView.contentMode = .scaleAspectFit
imageView.center = navController.navigationBar.center
navigationItem.titleView = imageView
}
//------------------------------------------------------------------------
and then set in viewdidload.
//------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
setUpNavigationBarTitleImage()
}
//------------------------------------------------------------------------
3. function " handler: " in UIAlertController must you know
handler as parameter, you can use like an example below
//------------------------------------------------------------------------
let ac = UIAlertController(title: "Open page…", message: nil, preferredStyle: .actionSheet)
ac.addAction(UIAlertAction(title: "apple.com", style: .default, handler: openPage))
....
func openPage(action: UIAlertAction) {
let url = URL(string: "https://" + action.title!)!
webView.load(URLRequest(url: url))
}
//------------------------------------------------------------------------
This method takes one parameter, which is the UIAlertAction object that was selected by the user. Obviously, it won't be called if Cancel was tapped, because that had a nil handler rather than openPage.
4. Remove separator last line use viewForFooterInSection
tableview just remove separator last line or last index
//------------------------------------------------------------------------
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView(frame: .zero)
}
//------------------------------------------------------------------------
https://stackoverflow.com/questions/44223810/last-static-cell-separator-line-appears-after-reloading-table-view
5. Height tableview dynamic by indexPath row
Is there any way by which I can get row height of each row in a UITableView. I have a UITableView which contains data which is dynamic, u can use in numberOfRowsInSection for dynamic and static use in viewdidload.
heightManual.constant = tableView.contentSize.height
6. How add separator to string at every 3 characters in swift?
use this extention for String must let variable
//------------------------------------------------------------------------
extension StringProtocol where Self: RangeReplaceableCollection {
mutating func insert(separator: Self, every n: Int) {
for index in indices.reversed() where index != startIndex &&
distance(from: startIndex, to: index) % n == 0 {
insert(contentsOf: separator, at: index)
}
}
func inserting(separator: Self, every n: Int) -> Self {
var string = self
string.insert(separator: separator, every: n)
return string
}
}ex:
let char = "5551190003451"
let account = char.inserting(separator: "-", every: 3)
print(account) // Result -> "555-119-000-345-1"
//------------------------------------------------------------------------
link : https://stackoverflow.com/a/34454633/8366535
7. String Attribute Swift 4.2
link : https://stackoverflow.com/a/32269975/8366535
This answer has been updated for Swift 4.2.
Quick Reference
The general form for making and setting an attributed string is like this. You can find other common options below.
// create attributed string
let myString = "Swift Attributed String"
let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
// set attributed text on a UILabel
myLabel.attributedText = myAttrString
let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]
let myAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myAttribute = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue ]
let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray
let myAttribute = [ NSAttributedString.Key.shadow: myShadow ]
The rest of this post gives more detail for those who are interested.
Attributes
String attributes are just a dictionary in the form of
[NSAttributedString.Key: Any]
, where NSAttributedString.Key
is the key name of the attribute and Any
is the value of some Type. The value could be a font, a color, an integer, or something else. There are many standard attributes in Swift that have already been predefined. For example:- key name:
NSAttributedString.Key.font
, value: aUIFont
- key name:
NSAttributedString.Key.foregroundColor
, value: aUIColor
- key name:
NSAttributedString.Key.link
, value: anNSURL
orNSString
There are many others. See this link for more. You can even make your own custom attributes like:
-
extension NSAttributedString.Key { static let myName = NSAttributedString.Key(rawValue: "myCustomAttributeKey") }
Creating attributes in Swift
You can declare attributes just like declaring any other dictionary.
// single attributes declared one at a time
let singleAttribute1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let singleAttribute2 = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
let singleAttribute3 = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]
// multiple attributes declared at once
let multipleAttributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.foregroundColor: UIColor.green,
NSAttributedString.Key.backgroundColor: UIColor.yellow,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]
// custom attribute
let customAttribute = [ NSAttributedString.Key.myName: "Some value" ]
Note the
rawValue
that was needed for the underline style value.
Because attributes are just Dictionaries, you can also create them by making an empty Dictionary and then adding key-value pairs to it. If the value will contain multiple types, then you have to use
Any
as the type. Here is the multipleAttributes
example from above, recreated in this fashion:var multipleAttributes = [NSAttributedString.Key : Any]()
multipleAttributes[NSAttributedString.Key.foregroundColor] = UIColor.green
multipleAttributes[NSAttributedString.Key.backgroundColor] = UIColor.yellow
multipleAttributes[NSAttributedString.Key.underlineStyle] = NSUnderlineStyle.double.rawValue
Attributed Strings
Now that you understand attributes, you can make attributed strings.
Initialization
There are a few ways to create attributed strings. If you just need a read-only string you can use
NSAttributedString
. Here are some ways to initialize it:// Initialize with a string only
let attrString1 = NSAttributedString(string: "Hello.")
// Initialize with a string and inline attribute(s)
let attrString2 = NSAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])
// Initialize with a string and separately declared attribute(s)
let myAttributes1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let attrString3 = NSAttributedString(string: "Hello.", attributes: myAttributes1)
If you will need to change the attributes or the string content later, you should use
NSMutableAttributedString
. The declarations are very similar:// Create a blank attributed string
let mutableAttrString1 = NSMutableAttributedString()
// Initialize with a string only
let mutableAttrString2 = NSMutableAttributedString(string: "Hello.")
// Initialize with a string and inline attribute(s)
let mutableAttrString3 = NSMutableAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])
// Initialize with a string and separately declared attribute(s)
let myAttributes2 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let mutableAttrString4 = NSMutableAttributedString(string: "Hello.", attributes: myAttributes2)
Changing an Attributed String
As an example, let's create the attributed string at the top of this post.
First create an
NSMutableAttributedString
with a new font attribute.let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myString = NSMutableAttributedString(string: "Swift", attributes: myAttribute )
If you are working along, set the attributed string to a
UITextView
(or UILabel
) like this:textView.attributedText = myString
You don't use
textView.text
.
Here is the result:
Then append another attributed string that doesn't have any attributes set. (Notice that even though I used
let
to declare myString
above, I can still modify it because it is an NSMutableAttributedString
. This seems rather unSwiftlike to me and I wouldn't be surprised if this changes in the future. Leave me a comment when that happens.)let attrString = NSAttributedString(string: " Attributed Strings")
myString.append(attrString)
Next we'll just select the "Strings" word, which starts at index
17
and has a length of 7
. Notice that this is an NSRange
and not a Swift Range
. (See this answer for more about Ranges.) The addAttribute
method lets us put the attribute key name in the first spot, the attribute value in the second spot, and the range in the third spot.var myRange = NSRange(location: 17, length: 7) // range starting at location 17 with a lenth of 7: "Strings"
myString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: myRange)
Finally, let's add a background color. For variety, let's use the
addAttributes
method (note the s
). I could add multiple attributes at once with this method, but I will just add one again.myRange = NSRange(location: 3, length: 17)
let anotherAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
myString.addAttributes(anotherAttribute, range: myRange)
Notice that the attributes are overlapping in some places. Adding an attribute doesn't overwrite an attribute that is already there.
8. Int To Date
Link: https://stackoverflow.com/questions/39934057/convert-date-to-integer-in-swift
Link: https://blog.apoorvmote.com/convert-date-to-string-vice-versa-in-swift/
Check Int to Date : https://www.epochconverter.com/
Date Helper: https://github.com/mikaelbo/AFDateHelper
Date
to Int
// using current date and time as an example
let someDate = Date()
// convert Date to TimeInterval (typealias for Double)
let timeInterval = someDate.timeIntervalSince1970
// convert to Integer
let myInt = Int(timeInterval)
Doing the
Double
to Int
conversion causes the milliseconds to be lost. If you need the milliseconds then multiply by 1000 before converting to Int
.
Int
to Date
Including the reverse for completeness.
ex:
let myInt = 1556334047174
// convert Int to Double
let timeInterval = Double(myInt)
// create NSDate from Double (NSTimeInterval)
let myNSDate = Date(timeIntervalSince1970: timeInterval)
I could have also used timeIntervalSinceReferenceDate
instead of timeIntervalSince1970
as long as I was consistent. This is assuming that the time interval is in seconds. Note that Java uses milliseconds.OR use this func:
9. Remove string <b> and </b> "Bold" from Html codeex: let myInt = 1556334047174
getDateFromStamp(myInt)
func getDateFromStamp(timeInterval:Int) -> String{ let date = NSDate(timeIntervalSince1970: TimeInterval(timeInterval / 1000)) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE, MMM dd, yyyy - HH:mm" let dateString = dateFormatter.string(from: date as Date) return dateString }
Swift Remove character from string, example:
//------------------------------------------------------------------------
let str = "<b>loream ipsum</b> dolor"
print(removeStrChar(str)) // loream ipsum dolor
func removeStrChar(_ str: String) -> String {
let removeStr = str.replace(string: "<b>", replacement: "")
let removeStr2 = removeStr.replace(string: "</b>", replacement: "")
return removeStr2
}
//------------------------------------------------------------------------
No comments: