How can I set two UITextFields together with Swift? - ios

I am trying to put two UITextFields with Swift together similar to this question: UITextField Set Border.
So the result should be one UITextField above the other and they will collapse on the border-bottom of the first one.
I am following the code that is on the question related:
tfUser.layer.borderWidth = 1
tfUser.layer.borderColor = UIColor(red: 69/255, green: 106/255, blue: 153/255, alpha: 1).CGColor
tfUser.layer.cornerRadius = 5
tfUser.clipsToBounds = true; //I am not able to equal this property to 'YES' so I put 'true'. Looking on the documentation I could see that it only accepts a boolean value.
tfPassword.layer.borderWidth = 2
tfPassword.layer.borderColor = UIColor(red: 69/255, green: 106/255, blue: 153/255, alpha: 1).CGColor
tfPassword.layer.cornerRadius = 5
tfPassword.clipsToBounds = true; //I am not able to equal this property to 'YES' so I put 'true'. Looking on the documentation I could see that it only accepts a boolean value.
I also have tried with the accepted answer but it does not recognize that property (I tried with borderStyle but it also does not work as I cannot set it to UITextBorderStyleNone).
The result I am getting right now is:
Am I missing something? What can I do to put them together?
Thanks in advance!

for your concept
step-1
Create One UIView and add the two textfield subview of UIVIew.
Step-2
set your yourTextField.borderStyle as None and set border width and border color
step-3
set the corner radius of UIView as UIView.layer.cornerRadius = 5
updated answer
you can downloaded the sample project in here
create one UIVIew, and two textfields and set your yourTextField.borderStyle = .None
#IBOutlet weak var backview: UIView!
#IBOutlet weak var txtUserName: UITextField!
#IBOutlet weak var txtpassword: UITextField!
and called in your page like
override func viewDidLoad() {
super.viewDidLoad()
self.changecornerRadius(self.txtpassword)
self.changecornerRadius(self.txtUserName)
self.changecornerRadiussd(self.backview)
}
func changecornerRadius(textfield: UITextField) {
textfield.layer.borderWidth = 1
textfield.layer.borderColor = UIColor.lightGrayColor().CGColor
textfield.layer.cornerRadius = 2
textfield.clipsToBounds = true
let paddingView = UIView(frame:CGRectMake(0, 0, 30, 30))
textfield.leftView=paddingView;
textfield.leftViewMode = .Always
}
func changecornerRadiussd(currentView: UIView) {
currentView.layer.borderWidth = 1
currentView.layer.borderColor = UIColor.blueColor().CGColor
currentView.layer.cornerRadius = 5
currentView.clipsToBounds = true
}
you get the output as

To set UITextBorderStyleNone in Swift:
yourTextField.borderStyle = .None

I think you have 3 solutions and both use UITextBorderStyleNon‌e:
add 2 background image
make grouped UITableView, cells should contain UITextFields
Draw it in frameRect method
I recommend to use number two

the best way to achieve this ..have a look below code
#IBAction func showLoginPasswordAlert(sender: UIButton) {
var alert = UIAlertController(title: "User login", message: "login password ..!!", preferredStyle:
UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler(configurationTextFieldLogin)
alert.addTextFieldWithConfigurationHandler(configurationTextFieldPassword)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
print("User click Ok button")
// print(self.textField.text)
}))
self.presentViewController(alert, animated: true, completion: {
print("completion block")
})
}
// func to add login textfield
func configurationTextFieldLogin(textField: UITextField!)
{
if let aTextField = textField {
textField.text = "Login"
}
}
// function to add password textfield
func configurationTextFieldPassword(textField: UITextField!)
{
if let aTextField = textField {
textField.text = "Password"
}
}
or you can edit in your best way..

Related

Why is the text color of my buttons not changing when I tap on them?

I want to change the text color of my UIButtons to .orange every time a user select one button to show which one is selected. It changes the color back to .white if another button is selected. I tried to subclass the buttons with the code below but nothing is changing. Using the storyboard and changing the color attribute in the inspector doesn´t work either. What am I missing?
class HighlightedButton: UIButton {
override var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? .orange : UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0)
}
}
override var isSelected: Bool {
didSet {
titleLabel?.textColor = isSelected ? .orange : .white
}
}
You can simply create an Outlet Collection for all the buttons in the stackView.
Add an #IBAction and connect all the buttons to it. In this method, set the selection of the tapped button. And change the textColor of all the buttons in the Outlet Collection based on their selection, i.e
#IBOutlet var buttons: [UIButton]!
#IBAction func onTapButton(_ sender: UIButton) {
buttons.forEach {
$0.isSelected = ($0 == sender)
$0.setTitleColor((sender.isSelected) ? .orange : .white, for: .normal)
}
}

UITextfield showing and dismissing very quickly in UIPageViewController (Swift)

I have a UIPageViewController as walkthrough presentation for my app. The walkthrough has basically 5 pages in total. Page 4 has a UITextField programmatically set. Don't mind the other objects like labels or Images.
The problem I have is that when the user reaches page 4, The user is presented with a Textfield which i'd like the keyboard to show up automatically via a becomeFirstResponder.
When I load this 4th view with the textfield, It shows up very quickly on the simulator and on my device and then goes back down. It basically shows up via the becomeFirstResponder code but somehow then resigns within 1 second.
I have tried this programmatically and also via the storyboard UITextfield to see if that made a difference but both seem to not work.
The code that executes a label is where I also executed the UITextField programmatically but for this example, I removed it and used an IBOutlet instead as you can see.
Also, in this case 3 I would put the becomeFirstResponder to activate the keyboard but it still did not work as expected.
Right now I left it in the viewWillAppear method as you can see.
Here is my code for this specific scenario:
import UIKit
class WalkthroughViewController: UIViewController {
#IBOutlet var headingLabel:UILabel!
#IBOutlet var contentLabel:UILabel!
#IBOutlet var contentImageView:UIImageView!
#IBOutlet var pageControl:UIPageControl!
#IBOutlet var forwardButton:UIButton!
// This was added via storyboard via drag and drop
#IBOutlet var nameField: UITextField!
// This is a UITextfield programmatically
let textField = UITextField(frame: CGRectMake(20, 200.0, 330.0, 40.0)) // x=x-cord, y=y-cord, Width, Height
// May 2 Updates
func textFieldFunc() {
textField.textAlignment = NSTextAlignment.Center
textField.textColor = UIColor.wetAsphaltColor()
textField.backgroundColor = UIColor.whiteColor()
textField.font = UIFont(name: "avenir", size: 21)
textField.borderStyle = UITextBorderStyle.None
textField.autocapitalizationType = UITextAutocapitalizationType.Words // If you need any capitalization
textField.becomeFirstResponder()
self.view.addSubview(textField)
}
func nameLabel() {
let label = UILabel(frame: CGRectMake(15, 180, 265, 33))
label.center = CGPointMake(185, 160)
label.textColor = UIColor.cloudsColor()
label.font = UIFont(name: "avenir", size: 30)
label.textAlignment = NSTextAlignment.Center
label.text = "Whats your name?"
self.view.addSubview(label)
}
#IBAction func submit(sender: AnyObject) {
// Thisis going to handle the name later and it will then reguster the user for later use within the app
}
var index = 0
var heading = ""
var imageFile = ""
var content = ""
override func viewDidLoad() {
super.viewDidLoad()
headingLabel.text = heading
contentLabel.text = content
contentImageView.image = UIImage(named: imageFile)
pageControl.currentPage = index
// 0...2
switch index {
case 0...2: forwardButton.setTitle("NEXT", forState: UIControlState.Normal)
nameField.hidden = true
// 3
case 3:
nameLabel()
nameField.hidden = false
case 4:
forwardButton.setTitle("DONE", forState: UIControlState.Normal)
default: break
}
print("Index: \(index)")
}
#IBAction func nextButtonTapped(sender: UIButton) {
switch index {
case 0...3: // 2
let pageViewController = parentViewController as! WalkthroughPageViewController
pageViewController.forward(index)
case 4: // 3
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(true, forKey: "finishedWalkedThrough")
dismissViewControllerAnimated(true, completion: nil)
default: break
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if nameField.hidden == false {
nameField.becomeFirstResponder()
}
}
}
My question is, how can I remedy this so that when the 4th page is presented in a slide through manner, the UITextfield can present the keyboard like a normal view?
As I saw in a very similar post, This actually worked. I managed to solve it by using this:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if index == 3 {
dispatch_async(dispatch_get_main_queue(), {() -> Void in
let strongSelf: WalkthroughViewController = self
strongSelf.textField.becomeFirstResponder()
})
}
}
Now when I scroll to the 4th page (3rd from 0), It loads the keyboard with the .becomeFirstResponder as a normal UITextField would.
dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), ^{
[self.yourTextField becomeFirstResponder];
});
For Swift 3:
DispatchQueue.main.async(execute: {() -> Void in
let strongSelf: WalkthroughViewController = self
strongSelf. textField.becomeFirstResponder()
})
I didn't have to specify the index position of the ViewController

PlaceHolder animates when start typing in TextField in iOS

How to set this type of animation in UITextField? Nowadays, Many apps are using this.
I've found the solution. You can manage this type of animation using multiple labels, and show-hide those labels into textFieldDidBeginEditing method.
If you want nice animation same as you describe into your question, then try once following third party repository for UITextField.
JVFloatLabeledTextField
UIFloatLabelTextField
FloatLabelFields
If you are looking for the UITextView equivalent of this animation, please visit UIFloatLabelTextView repository.
This problem can be solved logically with the use of multiple labels and text-fields and later we can add animation if needed. I will like to explain this problem using three images, namely Img1, Img2 and Img3.
Img1 points to storyboard, where we have designed our interface. Here we have used three Labels each followed by TextField and UIView(line below Textfield).
Img2: It points to the initial screen when the app launches or when we press the "Sign up" Button at the bottom, which resets the screen. In this Image, the labels are hidden as textfields are blank with and view color is gray.
Img3: This image reflects the editing of Textfield. As we start editing text field(here the first one, namely name), the label shows up, size of textfield decreases, placeholder changes and color of view changes to black.
We need to keep one more thing in mind, when we stop editing any textfield and if it is still blank then set it properties to original.
I am adding code for this Question which I was asked as assignment in an interview.
import UIKit
class FloatingLabelViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate {
//UITextFieldDelegate - protocol defines methods that you use to manage the editing and validation of text in a UITextField object. All of the methods of this protocol are optional.
//UINavigationControllerDelegate - Use a navigation controller delegate (a custom object that implements this protocol) to modify behavior when a view controller is pushed or popped from the navigation stack of a UINavigationController object.
#IBOutlet weak var NameLbl: UILabel!
#IBOutlet weak var EmailLbl: UILabel!
#IBOutlet weak var PasswordLbl: UILabel!
#IBOutlet weak var NameTxf: UITextField!
#IBOutlet weak var EmailTxf: UITextField!
#IBOutlet weak var PasswordTxf: UITextField!
#IBOutlet weak var SignUpBtn: UIButton!
#IBOutlet weak var NameView: UIView!
#IBOutlet weak var EmailView: UIView!
#IBOutlet weak var PasswordView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
NameTxf.delegate = self
EmailTxf.delegate = self
PasswordTxf.delegate = self
self.property()
//black is varaiable here
//setTitleColor - Sets the color of the title to use for the specified state
//var layer - The view’s Core Animation layer used for rendering. this propert is never nil
//cg color - Quartz color refernce
SignUpBtn.backgroundColor = UIColor.black
SignUpBtn.setTitleColor(UIColor.white, for: .normal)
SignUpBtn.layer.borderWidth = 1
SignUpBtn.layer.borderColor = UIColor.black.cgColor
//Tap guesture recognizer to hide keyboard
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(FloatingLabelViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
// UITapGestureRecognizer - UITapGestureRecognizer is a concrete subclass of UIGestureRecognizer that looks for single or multiple taps. For the gesture to be recognized, the specified number of fingers must tap the view a specified number of times.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//textFieldShouldReturn - Asks the delegate if the text field should process the pressing of the return button. The text field calls this method whenever the user taps the return button. YES if the text field should implement its default behavior for the return button; otherwise, NO.
// endEditing - Causes the view (or one of its embedded text fields) to resign the first responder status.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
//When user Starts Editing the textfield
// textFieldDidBeginEditing - Tells the delegate that editing began in the specified text field
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == self.NameTxf
{
self.NameTxf.font = UIFont.italicSystemFont(ofSize: 15)
self.NameLbl.isHidden = false
self.NameLbl.text = self.NameTxf.placeholder
self.NameTxf.placeholder = "First Last"
NameView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
}
else if textField == self.EmailTxf
{
self.EmailTxf.font = UIFont.italicSystemFont(ofSize: 15)
self.EmailLbl.isHidden = false
self.EmailLbl.text = self.EmailTxf.placeholder
self.EmailTxf.placeholder = "abc#gmail.com"
EmailView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
}
else if textField == self.PasswordTxf
{
self.PasswordTxf.font = UIFont.italicSystemFont(ofSize: 15)
self.PasswordLbl.isHidden = false
self.PasswordLbl.text = self.PasswordTxf.placeholder
self.PasswordTxf.placeholder = "........."
PasswordView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
}
}
//When User End editing the textfield.
// textFieldDidEndEditing - Tells the delegate that editing stopped for the specified text field.
func textFieldDidEndEditing(_ textField: UITextField) {
//Checkes if textfield is empty or not after after user ends editing.
if textField == self.NameTxf
{
if self.NameTxf.text == ""
{
self.NameTxf.font = UIFont.italicSystemFont(ofSize: 25)
self.NameLbl.isHidden = true
self.NameTxf.placeholder = "Name"
NameView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
}
else if textField == self.EmailTxf
{
if self.EmailTxf.text == ""
{
self.EmailTxf.font = UIFont.italicSystemFont(ofSize: 25)
self.EmailLbl.isHidden = true
self.EmailTxf.placeholder = "Email"
EmailView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
}
else if textField == self.PasswordTxf
{
if self.PasswordTxf.text == ""
{
self.PasswordTxf.font = UIFont.italicSystemFont(ofSize: 25)
self.PasswordLbl.isHidden = true
self.PasswordTxf.placeholder = "Password"
PasswordView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
}
}
//Action on SingUp button Clicked.
#IBAction func signupClicked(_ sender: Any) {
self.property()
self.dismissKeyboard() //TO dismiss the Keyboard on the click of SIGNUP button.
}
//Function to set the property of Textfields, Views corresponding to TextFields and Labels.
func property(){
NameLbl.isHidden = true
EmailLbl.isHidden = true
PasswordLbl.isHidden = true
NameTxf.text = ""
EmailTxf.text = ""
PasswordTxf.text = ""
NameTxf.placeholder = "Name"
EmailTxf.placeholder = "Email"
PasswordTxf.placeholder = "Password"
self.NameTxf.font = UIFont.italicSystemFont(ofSize: 25)
self.EmailTxf.font = UIFont.italicSystemFont(ofSize: 25)
self.PasswordTxf.font = UIFont.italicSystemFont(ofSize: 25)
EmailTxf.keyboardType = UIKeyboardType.emailAddress
PasswordTxf.isSecureTextEntry = true
NameTxf.autocorrectionType = .no
EmailTxf.autocorrectionType = .no
NameView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
EmailView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
PasswordView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
}
For Swift 4.0 and 4.2
Check this library for floating textField
https://github.com/hasnine/iOSUtilitiesSource
Code:
enum placeholderDirection: String {
case placeholderUp = "up"
case placeholderDown = "down"
}
public class IuFloatingTextFiledPlaceHolder: UITextField {
var enableMaterialPlaceHolder : Bool = true
var placeholderAttributes = NSDictionary()
var lblPlaceHolder = UILabel()
var defaultFont = UIFont()
var difference: CGFloat = 22.0
var directionMaterial = placeholderDirection.placeholderUp
var isUnderLineAvailabe : Bool = true
override init(frame: CGRect) {
super.init(frame: frame)
Initialize ()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
Initialize ()
}
func Initialize(){
self.clipsToBounds = false
self.addTarget(self, action: #selector(IuFloatingTextFiledPlaceHolder.textFieldDidChange), for: .editingChanged)
self.EnableMaterialPlaceHolder(enableMaterialPlaceHolder: true)
if isUnderLineAvailabe {
let underLine = UIImageView()
underLine.backgroundColor = UIColor.init(red: 197/255.0, green: 197/255.0, blue: 197/255.0, alpha: 0.8)
// underLine.frame = CGRectMake(0, self.frame.size.height-1, self.frame.size.width, 1)
underLine.frame = CGRect(x: 0, y: self.frame.size.height-1, width : self.frame.size.width, height : 1)
underLine.clipsToBounds = true
self.addSubview(underLine)
}
defaultFont = self.font!
}
#IBInspectable var placeHolderColor: UIColor? = UIColor.lightGray {
didSet {
self.attributedPlaceholder = NSAttributedString(string: self.placeholder! as String ,
attributes:[NSAttributedString.Key.foregroundColor: placeHolderColor!])
}
}
override public var placeholder:String? {
didSet {
// NSLog("placeholder = \(placeholder)")
}
willSet {
let atts = [NSAttributedString.Key.foregroundColor.rawValue: UIColor.lightGray, NSAttributedString.Key.font: UIFont.labelFontSize] as! [NSAttributedString.Key : Any]
self.attributedPlaceholder = NSAttributedString(string: newValue!, attributes:atts)
self.EnableMaterialPlaceHolder(enableMaterialPlaceHolder: self.enableMaterialPlaceHolder)
}
}
override public var attributedText:NSAttributedString? {
didSet {
// NSLog("text = \(text)")
}
willSet {
if (self.placeholder != nil) && (self.text != "")
{
let string = NSString(string : self.placeholder!)
self.placeholderText(string)
}
}
}
#objc func textFieldDidChange(){
if self.enableMaterialPlaceHolder {
if (self.text == nil) || (self.text?.count)! > 0 {
self.lblPlaceHolder.alpha = 1
self.attributedPlaceholder = nil
self.lblPlaceHolder.textColor = self.placeHolderColor
self.lblPlaceHolder.frame.origin.x = 0 ////\\
let fontSize = self.font!.pointSize;
self.lblPlaceHolder.font = UIFont.init(name: (self.font?.fontName)!, size: fontSize-3)
}
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {() -> Void in
if (self.text == nil) || (self.text?.count)! <= 0 {
self.lblPlaceHolder.font = self.defaultFont
self.lblPlaceHolder.frame = CGRect(x: self.lblPlaceHolder.frame.origin.x+10, y : 0, width :self.frame.size.width, height : self.frame.size.height)
}
else {
if self.directionMaterial == placeholderDirection.placeholderUp {
self.lblPlaceHolder.frame = CGRect(x : self.lblPlaceHolder.frame.origin.x, y : -self.difference, width : self.frame.size.width, height : self.frame.size.height)
}else{
self.lblPlaceHolder.frame = CGRect(x : self.lblPlaceHolder.frame.origin.x, y : self.difference, width : self.frame.size.width, height : self.frame.size.height)
}
}
}, completion: {(finished: Bool) -> Void in
})
}
}
func EnableMaterialPlaceHolder(enableMaterialPlaceHolder: Bool){
self.enableMaterialPlaceHolder = enableMaterialPlaceHolder
self.lblPlaceHolder = UILabel()
self.lblPlaceHolder.frame = CGRect(x: 0, y : 0, width : 0, height :self.frame.size.height)
self.lblPlaceHolder.font = UIFont.systemFont(ofSize: 10)
self.lblPlaceHolder.alpha = 0
self.lblPlaceHolder.clipsToBounds = true
self.addSubview(self.lblPlaceHolder)
self.lblPlaceHolder.attributedText = self.attributedPlaceholder
//self.lblPlaceHolder.sizeToFit()
}
func placeholderText(_ placeholder: NSString){
let atts = [NSAttributedString.Key.foregroundColor: UIColor.lightGray, NSAttributedString.Key.font: UIFont.labelFontSize] as [NSAttributedString.Key : Any]
self.attributedPlaceholder = NSAttributedString(string: placeholder as String , attributes:atts)
self.EnableMaterialPlaceHolder(enableMaterialPlaceHolder: self.enableMaterialPlaceHolder)
}
override public func becomeFirstResponder()->(Bool){
let returnValue = super.becomeFirstResponder()
return returnValue
}
override public func resignFirstResponder()->(Bool){
let returnValue = super.resignFirstResponder()
return returnValue
}
override public func layoutSubviews() {
super.layoutSubviews()
}
}
You can try using JSInputField which supports data validations as well.
JSInputField *inputField = [[JSInputField alloc] initWithFrame:CGRectMake(10, 100, 300, 50)];
[self.view addSubview:inputField];
[inputField setPlaceholder:#"Enter Text"];
[inputField setRoundedCorners:UIRectCornerAllCorners];
[inputField addValidationRule:JSCreateRuleNotNullValue]; //This will validate field for null value. It will show error if field is empty.
[inputField addValidationRule:JSCreateRuleNumeric(2)]; //This will validate field for numeric values and restrict to enter value upto 2 decimal places.
You can use SkyFloatingLabelTextField. It is SkyScanner's library for this kind of label or textField animations.
https://github.com/Skyscanner/SkyFloatingLabelTextField
I hope this answer will works for you.
Enjoy.
use this code
[your_textfieldname setShowsTouchWhenHighlighted:YES];

Swift and Xcode - How to Create Custom Tab Bar Icons

I have a tabbed application project I am working on in Xcode written in Swift (Xcode 6.3 and Swift 1.2). I am having a lot of trouble with custom Tab Bar icons. I have designed an image in Photoshop (CS6), saved it as a PNG, resized it in Prepo to be 30x30 and imported it into Xcode in the asset library. I then set the tab view controllers icon to that image. However, it doesn't show up.
I have looked at these pages but not found any help:
https://www.youtube.com/watch?v=4qqqoAWNfZA
Custom tab bar icon colors
http://www.raywenderlich.com/forums/viewtopic.php?f=2&t=19333
http://www.appcoda.com/ios-programming-how-to-customize-tab-bar-background-appearance/
https://www.youtube.com/watch?v=4Tj_SeApUrs
What is the proper process to create custom tab bar icons?
After a bit of research I resolved the issue, so thought I'd post here in case anyone else has a similar issue. In Photoshop I did the following:
Imported the image I wanted to use as the tab bar icon (its easier if you use a black and white image so that you don't have to remove colour).
Set the background to 'Transparent' rather than white.
Removed all white from the image so that it was just a black image with a transparent background.
Saved the image as a .png.
Resized the image to be a square with dimensions 75x75 pixels (and named imageName#3x.png), 50x50 pixels (and named imageName#2x.png), and 25x25 pixels (and named imageName.png)
In Xcode I did the following:
Dragged the images into Xcode and renamed the image group as icoImageName.
Selected the tab I wanted to set the image for in the storyboard in Xcode and set the 'Image' (under 'Bar Item' in the Inspector Pane) to icoImageName. Note that I did not set the 'Selected Image' under the 'Tab Bar Item' (leave this blank).
Done.
I hope this helps someone. Thanks to everyone for their help as well.
It sounds like you have everything set up properly in xCode. The problem IS the png file you are using.
Download this image, http://i.stack.imgur.com/zluev.png , and see if the problem persists.
According to an answer on UITabBarItem images just appear as a grey block:
The standard tabbar icons in iOS are rendered solely from the alpha channel. Colors are ignored completely. Instead of colors you can use different alpha values that lead to a different shade of gray (or blue if selected)
Make the background of your icons transparent.
Did you create the tab view in interface builder? If so, since you added the images as an asset they should show up in the 'Image' property of each tab button under the inspector sidebar. Also, I know you've already posted a ton of tutorials, but this one is pretty up to date and explains it thoroughly: http://codewithchris.com/ios-tab-bar-app/
class ViewController: UIViewController {
#IBOutlet var btnHome : UIButton!
#IBOutlet var btnInvoice : UIButton!
#IBOutlet var btnSettings : UIButton!
#IBOutlet var btnMyOrder : UIButton!
#IBOutlet var btnLogout : UIButton!
#IBOutlet weak var viewContainer: UIView!
var navController : UINavigationController!
var selectedIndex : Int! = 0
var arrTabColor = [UIColor(red: 35.0/255.0, green: 93.0/255.0, blue: 175.0/255.0, alpha: 1.0),
UIColor(red: 29.0/255.0, green: 86.0/255.0, blue: 167.0/255.0, alpha: 1.0),
UIColor(red: 35.0/255.0, green: 93.0/255.0, blue: 175.0/255.0, alpha: 1.0),
UIColor(red: 29.0/255.0, green: 86.0/255.0, blue: 167.0/255.0, alpha: 1.0),
UIColor(red: 35.0/255.0, green: 93.0/255.0, blue: 175.0/255.0, alpha: 1.0)]
var arrTabIdentiFierVC = ["FirstVC","SecondVC","FirstVC","FirstVC","SecondVC"]
// MARK: - Life Cycle
override func viewDidLoad()
{
super.viewDidLoad()
setTabbarImage(0)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setTabBarClicked(_ storyIdentifier : String,identifier : String)
{
let aStoryboard = UIStoryboard.init(name: storyIdentifier, bundle: nil)
let newViewController = aStoryboard.instantiateViewController(withIdentifier: identifier)
navController = UINavigationController(rootViewController: newViewController)
self.addChildViewController(navController)
navController.view.frame = viewContainer.frame
newViewController.view.frame = viewContainer.frame
self.viewContainer.addSubview(navController.view)
newViewController.didMove(toParentViewController: self)
}
func setTabbarImage(_ selectedIndex : Int!)
{
btnHome.backgroundColor = arrTabColor[0]
btnInvoice.backgroundColor = arrTabColor[1]
btnSettings.backgroundColor = arrTabColor[2]
btnMyOrder.backgroundColor = arrTabColor[3]
btnLogout.backgroundColor = arrTabColor[4]
let selectedColor = UIColor(red: 40/255, green: 142/255, blue: 206.0/255, alpha: 1.0)
if selectedIndex == 0
{
btnHome.backgroundColor = selectedColor
}
else if selectedIndex == 1
{
btnInvoice.backgroundColor = selectedColor
}
else if selectedIndex == 2
{
btnSettings.backgroundColor = selectedColor
}
else if selectedIndex == 3
{
btnMyOrder.backgroundColor = selectedColor
}
else if selectedIndex == 4
{
btnLogout.backgroundColor = selectedColor
}
}
// MARK: - Action Method
#IBAction func HomeClicked(_ sender : AnyObject?)
{
setTabbarImage(0)
setTabBarClicked("Main",identifier: arrTabIdentiFierVC[0])
}
#IBAction func InvoiceClicked(_ sender : AnyObject?)
{
setTabbarImage(1)
setTabBarClicked("Main",identifier: arrTabIdentiFierVC[1])
}
#IBAction func SettingClicked(_ sender : AnyObject?)
{
setTabbarImage(2)
setTabBarClicked("Main",identifier: arrTabIdentiFierVC[2])
}
#IBAction func MyorderClicked(_ sender : AnyObject?)
{
setTabbarImage(3)
setTabBarClicked("Main",identifier: arrTabIdentiFierVC[3])
}
#IBAction func logoutClicked(_ sender : AnyObject?)
{
setTabbarImage(4)
let alert = UIAlertController(title: "", message: "Are you sure want to logout?", preferredStyle: UIAlertControllerStyle.alert)
let CancelAction = UIAlertAction(title: "NO", style: .default) { (action:UIAlertAction!) in
}
alert.addAction(CancelAction)
let OKAction = UIAlertAction(title: "YES", style: .default) { (action:UIAlertAction!) in
// var isNav : Bool! = false
//for objChild in (self.parent?.childViewControllers)!
// {
// if objChild.isKind(of: LoginVC.self)
// {
// self.navigationController!.popToViewController(objChild, animated: true)
// CommonMethods.removeCustomObject(Constants.kUserProfile)
//
// isNav = true
// break
//
// }
// }
// if !isNav
// {
// CommonMethods.removeCustomObject(Constants.kUserProfile)
// let aNavController = (AppDelegate.getDelegate().window!.rootViewController! as! UINavigationController)
// let storyboard = UIStoryboard(name: "Main", bundle: nil)
// var aVCObj = UIViewController()
// aVCObj = storyboard.instantiateViewController(withIdentifier: "LoginVC")
// var aMutArr = aNavController.viewControllers
// aMutArr.insert(aVCObj, at: 0)
// aNavController.viewControllers = aMutArr
// aNavController.popToRootViewController(animated: true)
// }
}
alert.addAction(OKAction)
self.present(alert, animated: true, completion: nil)
}
// MARK: - Action Method
}

TTTAttributedLabel Link detecting not work in iOS8 with swift

I want to use TTTAttributedLabel to detect the link of the text in the Label of UITableViewCell, but it doesn't work. I'm using swift with iOS8. below is UITableViewCell code:
class StoryTableViewCell: UITableViewCell, TTTAttributedLabelDelegate {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// Link properties
let textLabel = self.descriptionLabel
let linkColor = UIColor(red: 0.203, green: 0.329, blue: 0.835, alpha: 1)
let linkActiveColor = UIColor.blackColor()
if (textLabel is TTTAttributedLabel) {
var label = textLabel as TTTAttributedLabel
label.linkAttributes = [NSForegroundColorAttributeName : linkColor]
label.activeLinkAttributes = [NSForegroundColorAttributeName : linkActiveColor]
label.enabledTextCheckingTypes = NSTextCheckingType.Link.toRaw()
label.delegate = self
}
}
}
I think you have not configured your custom cell correctly.
First at your customCell declare and connect your IBOutlet-s. Select your textLabel and add its class to TTTAttributedLabel. Your custom cell should look like this:
class StoryTableViewCell: UITableViewCell {
#IBOutlet weak var textLabel: TTTAttributedLabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Second you need to add the TTTAttributedLabelDelegate at the class where you are using the tableView datasource and delegate.
Then under cellForRowAtIndexPath
var cell: StoryTableViewCell = tableView.dequeueReusableCellWithIdentifier("yourCellIdentifier") as StoryTableViewCell
let linkColor = UIColor(red: 0.203, green: 0.329, blue: 0.835, alpha: 1)
let linkActiveColor = UIColor.blackColor()
cell.textLabel.delegate = self
cell.textLabel.linkAttributes = [kCTForegroundColorAttributeName : linkColor]
cell.textLabel.activeLinkAttributes = [kCTForegroundColorAttributeName : linkActiveColor]
cell.textLabel.enabledTextCheckingTypes = NSTextCheckingType.Link.rawValue
Then if you have methods that need to be executed from TTTAttributedLabelDelegate add them and do your calculations.
Hope it helps
If you've set TTTAttributedLabel as the class of your UILabel, within a nib or the storyboard, make sure User Interaction Enabled is set to true, as be default a UILabel will have user interaction disabled.
let linkColor = UIColor.blueColor()
let linkActiveColor = UIColor.greenColor()
textLabel.delegate = self
textLabel.linkAttributes = [kCTForegroundColorAttributeName : linkColor.CGColor,kCTUnderlineStyleAttributeName : NSNumber(bool: true)]
textLabel.activeLinkAttributes = [NSForegroundColorAttributeName : linkActiveColor]
textLabel.enabledTextCheckingTypes = NSTextCheckingType.Link.rawValue
swift 4.2
label.enabledTextCheckingTypes = NSTextCheckingResult.CheckingType.link.rawValue | NSTextCheckingResult.CheckingType.phoneNumber.rawValue
Nothing works for me finally i put below code in TTTAttributedLabel.m in commonInit() method
self.enabledTextCheckingTypes = NSTextCheckingTypeLink;

Resources