I'm using Xcode 11.2 and Swift 5 with the latest version of SwipeCellKit.
In my code, I have a UITableView with cells in it. I wish to add swipe action from the right, which will let me use two actions: delete and edit.
For now, I'm trying only the delete action. However, the swipe doesn't seem to be working, I get no actions at all.
What am I missing here?
Here's my code:
CartTableViewCell
import UIKit
import SwipeCellKit
class CartTableViewCell: SwipeTableViewCell
{
#IBOutlet weak var mainView: UIView!
#IBOutlet weak var productName: UILabel!
#IBOutlet weak var productImage: UIImageView!
#IBOutlet weak var priceForKg: UILabel!
#IBOutlet weak var quantity: UITextField!
#IBOutlet weak var subTotal: UITextField!
override func awakeFromNib()
{
super.awakeFromNib()
self.layer.borderWidth = 1
self.layer.cornerRadius = 25
self.layer.borderColor = self.layer.backgroundColor
self.mainView.layer.borderWidth = 1
self.mainView.layer.cornerRadius = 25
self.mainView.layer.borderColor = self.mainView.layer.backgroundColor
self.quantity.layer.borderWidth = 1
self.quantity.layer.borderColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
self.quantity.layer.cornerRadius = 5
self.subTotal.layer.borderWidth = 1
self.subTotal.layer.borderColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
self.subTotal.layer.cornerRadius = 5
}
override var frame: CGRect {
get {
return super.frame
}
set (newFrame) {
var frame = newFrame
frame.origin.y += 4
frame.size.height -= 2 * 5
super.frame = frame
}
}
override func setSelected(_ selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
}
}
CartViewController
import UIKit
import SwipeCellKit
class CartViewController: UIViewController
{
#IBOutlet weak var cartTableView: UITableView!
var listOfProducts : [Product] = []
override func viewDidLoad()
{
super.viewDidLoad()
self.cartTableView.delegate = self
self.cartTableView.dataSource = self
self.cartTableView.separatorStyle = .none
self.cartTableView.allowsSelection = false
self.cartTableView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
self.subTotalView.layer.borderWidth = 1
self.subTotalView.layer.borderColor = self.subTotalView.layer.backgroundColor
self.subTotalView.layer.cornerRadius = 10
let cellNib = UINib(nibName: "CartTableViewCell", bundle: nil)
self.cartTableView.register(cellNib, forCellReuseIdentifier: "cartProductCell")
}
}
extension CartViewController : UITableViewDelegate, UITableViewDataSource, SwipeTableViewCellDelegate
{
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]?
{
guard orientation == .right else { return nil }
let deleteAction = SwipeAction(style: .destructive, title: "Delete")
{
action, indexPath in
// handle action by updating model with deletion
}
// customize the action appearance
deleteAction.image = UIImage(named: "Delete")
return [deleteAction]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return listOfProducts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cartProductCell", for: indexPath) as! CartTableViewCell
return cell
}
}
I found the answer, if any of you guys are looking for it, the missing line is to set the delegate of the cell before returning it:
cell.delegate = self
As mentioned in this post:
SwipeCellKit Swipe to delete not being called
Related
I have a navigationController in my first storyboard. From that storyboard, I push a new viewController onto the stack but its in a different storyboard. When I try to change the background image for my secondviewController only, it doesn't work.
In my first viewController, I programmatically segue to UsersViewController, which is my second VC. Here is my first view controller and storyboard:
import UIKit
class HomeViewController: UIViewController {
#IBOutlet weak var welcomeLabel: UILabel!
#IBOutlet weak var splitLabel: UIButton!
#IBOutlet weak var rouletteLabel: UIButton!
#IBOutlet weak var quickLabel: UIButton!
#IBOutlet weak var buttonStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
welcomeLabel.font = UIFont(name: Theme.headingFontName, size: 32)
splitLabel.titleLabel?.font = UIFont(name: Theme.mainFontName, size: 26)
splitLabel.backgroundColor = Theme.accent
splitLabel.layer.cornerRadius = 10
rouletteLabel.titleLabel?.font = UIFont(name: Theme.mainFontName, size: 26)
rouletteLabel.backgroundColor = Theme.delete
rouletteLabel.layer.cornerRadius = 10
quickLabel.titleLabel?.font = UIFont(name: Theme.mainFontName, size: 26)
quickLabel.backgroundColor = Theme.edit
quickLabel.layer.cornerRadius = 10
}
#IBAction func splitNavigation(_ sender: Any) {
let storyboard = UIStoryboard(name: String(describing: UsersViewController.self), bundle: nil)
let vc = storyboard.instantiateInitialViewController()!
navigationController?.pushViewController(vc, animated: true)
}
}
In my UsersViewController, I try to change the background image of the navigationbar:
import UIKit
class UsersViewController: UIViewController {
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var viewContainer: UIView!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var nextBtn: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
setup()
}
func setup() {
view.backgroundColor = Theme.background
nameTextField.borderStyle = .none
nameTextField.backgroundColor = .clear
nameTextField.underlined()
viewContainer.backgroundColor = .white
viewContainer.layer.cornerRadius = 40
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "People"
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "navBar"), for: .default)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toAddUserVC" {
let popup = segue.destination as! AddUsersViewController
popup.doneSaving = { [weak self] in
self?.tableView.reloadData()
}
}
}
}
extension UsersViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Data.userModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! UsersTableViewCell
let model = Data.userModels[indexPath.row]
cell.setup(userModel: model)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
}
extension UITextField {
func underlined(){
let border = CALayer()
let width = CGFloat(1.0)
border.borderColor = UIColor.lightGray.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}
I don't know why, but every time I navigate to the UsersViewController, the background image flashes for a quick second, and then disappears. The title and bar buttons still show. Then, if I navigate back to the first viewController, the NavigationBar is gone. Here is a gif of what happens when I try to run the code if that helps.
via GIPHY
I'm able to change the color, the translucence, and every other property of the navigationbar, expect this. I figure it something to do with the fact that it's in a different storyboard. Any help is appreciated! Thank you!
I'm trying to using CallKit to add a feature to my app to add some phone numbers to blacklist!
the code below is my whole view!!
class BlacklistViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate {
var phoneNumbersArrCoreData = [BlockedPhoneNumbers]()
var listPhoneNumbers:[CXCallDirectoryPhoneNumber] = []
#IBOutlet weak var TableView: UITableView!
#IBOutlet weak var BtnAddO: UIButton!
#IBOutlet weak var EntPhonenumber: UITextField!
#IBAction func BtnAddA(_ sender: Any) {
if !(EntPhonenumber.text?.isEmpty)!
{
let blackedPhonenumbers_CoreData = BlockedPhoneNumbers(context: PersistanceService.context)
blackedPhonenumbers_CoreData.phoneNumber = Int64.init(EntPhonenumber.text!)!
PersistanceService.saveContext()
getCoreData()
TableView.reloadData()
}
}
var coreData = [BlockedPhoneNumbers]()
func getCoreData()
{
listPhoneNumbers.removeAll()
let fetchRequest : NSFetchRequest<BlockedPhoneNumbers> = BlockedPhoneNumbers.fetchRequest()
do
{
let FetchedResultFromDB = try PersistanceService.context.fetch(fetchRequest)
coreData = FetchedResultFromDB
print("============\n===========\n")
if coreData.count > 0
{
for i in 0..<coreData.count
{
listPhoneNumbers.append(coreData[i].phoneNumber)
}
}
print("============\n===========\n")
}
catch{
print("gettin blocked number from db got error")
}
}
override func viewDidLoad() {
BtnAddO.layer.cornerRadius = 5
BtnAddO.layer.borderColor = UIColor.white.cgColor
BtnAddO.layer.borderWidth = 0.8
EntPhonenumber.attributedPlaceholder = NSAttributedString(string: "Enter a phone number to block",attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightText])
getCoreData()
super.viewDidLoad()
view.backgroundColor = UIColor.init(red: 25/255, green: 28/255, blue: 46/255, alpha: 1)
TableView.delegate = self
TableView.dataSource = self
}
func beginRequest(with context: CXCallDirectoryExtensionContext) {
getCoreData()
let blockedPhoneNumbers: [CXCallDirectoryPhoneNumber] = listPhoneNumbers
for phoneNumber in blockedPhoneNumbers.sorted(by: <) {
context.addBlockingEntry(withNextSequentialPhoneNumber: phoneNumber)
}
context.completeRequest()
}
//MARK: - TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listPhoneNumbers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BlackListCell") as? BlackListTableViewCell
cell?.ContactImg.layer.masksToBounds = true
cell?.mainView.layer.cornerRadius = 10
cell?.mainView.backgroundColor = UIColor(red: 42/255, green: 48/255, blue: 66/255, alpha: 1)
cell?.ContactImg.layer.cornerRadius = 5
cell?.ContactImg.image = UIImage(named: "Blocked")
cell?.unBlock.imageView?.image = nil
cell?.unBlock.setTitle("UNBLOCK", for: UIControl.State.normal)
cell?.unBlock.layer.cornerRadius = (cell?.unBlock.frame.size.height)!/2
cell?.SetUnblockBtn {
I get the error here,below
let context:NSManagedObjectContext = PersistanceService.context
context.delete(self.phoneNumbersArrCoreData[indexPath.row] as NSManagedObject)
self.phoneNumbersArrCoreData.remove(at: indexPath.row)
print("data deleted!!!")
}
cell?.phoneNumber.text = String(listPhoneNumbers[indexPath.row])
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
}
to explain the code, I save each number that user will enter in a core data(entityName: BlockedPhoneNumbers). I'm not sure even if this is the right way to save numbers that they need to be blocked or not!!
when the user presses the button I save the number and it works fine( but I'm not sure if this is the right way or not!!).
and in getCoreData I get the core data and show them in a table view. which shows that core data works fine! but when user wanna unblock the contact and presses the button in CELL of the table view, I get an error and app crash and it says:
Thread 1: Fatal error: Index out of range
my problems are:
why do I get this error?
2.as I can not find any tutorial for callKit I believe that I'm doing this job wrong.
could anyone help me with this?
You have too many arrays:
listPhoneNumbers which contains your integer numbers
coreData which contains your Core Data items
phoneNumbersArrCoreData which could contain your Core Data items, but you don't add anything to it.
As a result, phoneNumbersArrCoreData is empty. When you try and remove an object from the empty array you get an array bounds exception.
You should eliminate two of the three arrays.
class BlacklistViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate {
var blockedNumbers = [BlockedPhoneNumbers]()
#IBOutlet weak var TableView: UITableView!
#IBOutlet weak var BtnAddO: UIButton!
#IBOutlet weak var EntPhonenumber: UITextField!
#IBAction func BtnAddA(_ sender: Any) {
if !(EntPhonenumber.text?.isEmpty)!
{
let blackedPhonenumbers_CoreData = BlockedPhoneNumbers(context: PersistanceService.context)
blackedPhonenumbers_CoreData.phoneNumber = Int64.init(EntPhonenumber.text!)!
PersistanceService.saveContext()
getCoreData()
TableView.reloadData()
}
}
func getCoreData()
{
let fetchRequest : NSFetchRequest<BlockedPhoneNumbers> = BlockedPhoneNumbers.fetchRequest()
do
{
let FetchedResultFromDB = try PersistanceService.context.fetch(fetchRequest)
blockedNumbers = FetchedResultFromDB
print("============\n===========\n")
}
catch{
print("gettin blocked number from db got error")
}
}
override func viewDidLoad() {
BtnAddO.layer.cornerRadius = 5
BtnAddO.layer.borderColor = UIColor.white.cgColor
BtnAddO.layer.borderWidth = 0.8
EntPhonenumber.attributedPlaceholder = NSAttributedString(string: "Enter a phone number to block",attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightText])
getCoreData()
super.viewDidLoad()
view.backgroundColor = UIColor.init(red: 25/255, green: 28/255, blue: 46/255, alpha: 1)
TableView.delegate = self
TableView.dataSource = self
}
//MARK: - TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return blockedNumbers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BlackListCell") as? BlackListTableViewCell
cell?.ContactImg.layer.masksToBounds = true
cell?.mainView.layer.cornerRadius = 10
cell?.mainView.backgroundColor = UIColor(red: 42/255, green: 48/255, blue: 66/255, alpha: 1)
cell?.ContactImg.layer.cornerRadius = 5
cell?.ContactImg.image = UIImage(named: "Blocked")
cell?.unBlock.imageView?.image = nil
cell?.unBlock.setTitle("UNBLOCK", for: UIControl.State.normal)
cell?.unBlock.layer.cornerRadius = (cell?.unBlock.frame.size.height)!/2
cell?.SetUnblockBtn {
let context:NSManagedObjectContext = PersistanceService.context
context.delete(self.blockedNumbers[indexPath.row] as NSManagedObject)
self.phoneNumbersArrCoreData.remove(at: indexPath.row)
print("data deleted!!!")
}
cell?.phoneNumber.text = blockedNumbers[indexPath.row].phoneNumber
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
}
The code to actually load data into the Call Kit block list needs to go into a CallKit extension in your app. You will need to use an application group to share the Core Data store with the extension.
I am new to code, and I just can't find the solution to this problem. Most of the answers on the internet are deprecated or unanswered.
I want to search something into my searchbar, after that I want to press on one of the results. When I click on the result I want it to give me the corresponding information in another viewcontroller.
Here's my problem: When I click on a result, the information in the other viewcontroller doesn't correspond with the information that the result gave me. What he does gives me is the information that corresponds to the tableview. So, it segues with a wrong index. Does anyone knows what the solution is?
Here's my code (tableviewcontroller with searchbar):
var myIndex = 0
extension UIColor { //themakleur
static let candyGreen = UIColor(red: 71.0/255.0, green: 81.0/255.0, blue:
89.0/255.0, alpha: 1.0)}
var watjeberekend = ["Omtrek Cirkel","Oppervlakte Cirkel","Lengte
Boog","Oppervlakte Sector","Oppervlakte Bol"]
class scheikunde: UITableViewController, UISearchResultsUpdating {
var scheikundeformules = ["Omtrek Cirkel","Oppervlakte Cirkel","Lengte Boog","Oppervlakte Sector","Oppervlakte Bol"]
var searchcontroller : UISearchController!
var filterednamen = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.searchcontroller = UISearchController(searchResultsController: nil)
self.tableView.tableHeaderView = self.searchcontroller.searchBar
self.searchcontroller.searchResultsUpdater = self
self.searchcontroller.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
self.navigationItem.hidesBackButton = false;
self.navigationController?.isNavigationBarHidden = false
//navigationcontroller layout
navigationController?.navigationBar.barTintColor = UIColor(red: 71.0/255.0, green: 81.0/255.0, blue: 89.0/255.0, alpha: 1.0)
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
navigationController?.navigationBar.layer.borderColor = UIColor.candyGreen.cgColor
navigationController?.navigationBar.layer.borderWidth = 0
//searchcontroller layout
searchcontroller.searchBar.layer.borderWidth = 0
searchcontroller.searchBar.layer.borderColor = UIColor.candyGreen.cgColor
UISearchBar.appearance().barTintColor = .candyGreen
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = .candyGreen
searchcontroller.searchBar.backgroundImage = UIImage(named: "themakleur.jpg")
let cancelButtonAttributes: [String: AnyObject] = [NSForegroundColorAttributeName: UIColor.white]
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal)
}
func updateSearchResults(for searchController: UISearchController) {
self.filterednamen = self.scheikundeformules.filter { (naam : String) -> Bool in
if naam.lowercased().contains(self.searchcontroller.searchBar.text!.lowercased()) {
return true
}else{
return false}}
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !searchcontroller.isActive || searchcontroller.searchBar.text == "" {
return self.scheikundeformules.count
}else {
return self.filterednamen.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Custommath
cell.label.text = scheikundeformules[indexPath.row]
if !searchcontroller.isActive || searchcontroller.searchBar.text == "" {
//cell.textLabel?.text = self.namen[indexPath.row]
cell.label.text = self.scheikundeformules[indexPath.row]
}else{
//cell.textLabel?.text = self.filterednamen[indexPath.row]
cell.label.text = self.filterednamen[indexPath.row]
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
performSegue(withIdentifier: "segue", sender: self)
}
}
Here is my code from the viewcontroller:
import UIKit
class scheikundeformule: UIViewController{
#IBOutlet var uitleg6: UILabel!
#IBOutlet var formuleomschrijving: UILabel!
#IBOutlet var uitleg5: UILabel!
#IBOutlet var uitleg4: UILabel!
#IBOutlet var uitleg3: UILabel!
#IBOutlet var uitleg2: UILabel!
#IBOutlet var uitleg1: UILabel!
#IBOutlet var titlelabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
titlelabel.text = scheikundeformules[myIndex]
uitleg1.text = uitlegformules2[myIndex]
uitleg2.text = uitlegformules3[myIndex]
uitleg3.text = uitlegformules4[myIndex]
uitleg4.text = uitlegformules5[myIndex]
uitleg5.text = uitlegformules6[myIndex]
uitleg6.text = uitlegformules7[myIndex]
self.navigationItem.hidesBackButton = false;
self.navigationController?.isNavigationBarHidden = false
formuleomschrijving.text = watjeberekend[myIndex]
//keyboard weg deel 1
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(startscreen.dismissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
Where is your function prepare for segue ? if you want to pass the data to the next view controller you need to send it in the fun prepare for segue, and remember that the indexpath.row needs to be used with the array that is the current datasource of the tableview, the solution will be something like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationVC = segue.destination as? YourViewController {
if !searchcontroller.isActive {
destinationVC.name = filterednamen[myIndex]
} else {
destinationVC.name = scheikundeformules[myIndex]
} }
}
Add identifier for scheikundeformule view controller in storyboard like below :
Step 1:
Step 2:
change your tableview didSelectRow like below :
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
let scheikundeformuleController = self.storyboard?.instantiateViewController(withIdentifier: "scheikundeformule") as! scheikundeformule
scheikundeformuleController.myIndex = indexPath.row
self.present(scheikundeformuleController, animated: true, completion: nil)
}
Step 3:
You have to add var myIndex = 0 to your scheikundeformule controller. Like below :
class scheikundeformule: UIViewController{
var myIndex = 0
........Your code
}
I am creating a little Task list application using Xcode 7 and Swift. However, I want some of the data, such as the date label, to be on the right side of the UITableViewCell, except for the left. What code would I use to put the date label on the right side of a UITableViewCell?
Here is my code for my ViewController.swift, that has the TableView.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// All Outlets Connected to StoryBoard
#IBOutlet var BTN: UIButton!
#IBOutlet var BTN2: UIButton!
#IBOutlet var BTN3: UIButton!
#IBOutlet var BTN4: UIButton!
#IBOutlet var tbl: UITableView?
#IBOutlet var Button: UIBarButtonItem!
#IBOutlet var Bar: UINavigationItem!
//Other Variables
var varView = Int()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.\
if revealViewController() != nil {
Button.target = revealViewController()
Button.action = #selector(SWRevealViewController.revealToggle(_:))
}
self.view.backgroundColor = UIColor(red: 50 / 255.0, green: 132 / 255.0, blue: 255 / 255.0, alpha: 1.0)
BTN.alpha = 1.0
BTN4.alpha = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func BTNClicked(sender: AnyObject) {
UIView.animateWithDuration(1.0, animations: ({
self.BTN2.transform = CGAffineTransformMakeTranslation(0, -90)
self.BTN3.transform = CGAffineTransformMakeTranslation(0, -180)
self.BTN4.transform = CGAffineTransformMakeTranslation(0, 0)
self.BTN.alpha = 0
self.BTN4.alpha = 1.0
}))
}
#IBAction func BTNClickedAgain(sender: AnyObject) {
UIView.animateWithDuration(1.0, animations: ({
self.BTN2.transform = CGAffineTransformMakeTranslation(0, 0)
self.BTN3.transform = CGAffineTransformMakeTranslation(0, 0)
self.BTN4.transform = CGAffineTransformMakeTranslation(0, 0)
self.BTN.alpha = 1.0
self.BTN4.alpha = 0
}))
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
if(editingStyle == UITableViewCellEditingStyle.Delete){
taskMgr.tasks.removeAtIndex(indexPath.row)
tbl?.reloadData();
}
}
override func viewWillAppear(animated: Bool) {
tbl?.reloadData();
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return taskMgr.tasks.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell{
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "test")
cell.textLabel?.text = taskMgr.tasks[indexPath.row].name
cell.detailTextLabel?.text = taskMgr.tasks[indexPath.row].desc
cell.detailTextLabel?.text = taskMgr.tasks[indexPath.row].date
return cell
}
Also, here is a look at my AddPlan.swift, this is where I add the Data to the UITableViewCells in the ViewControlelr.swift:
class addPlan: UIViewController, UITextFieldDelegate {
var time: Int = 6
#IBOutlet var txt: UITextField!
#IBOutlet var txt2: UITextField! // This is the data text, I want this to be on the left side of the UITableViewCell.
#IBOutlet var txt1: UITextField!
#IBOutlet var Button02: UIBarButtonItem!
override func viewDidLoad() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(addPlan.dismissKeyboard))
view.addGestureRecognizer(tap)
self.txt.delegate = self;
self.txt1.delegate = self;
self.txt2.delegate = self;
if revealViewController() != nil {
Button02.target = revealViewController()
Button02.action = #selector(SWRevealViewController.revealToggle(_:))
}
}
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)
}
#IBAction func ClickedforSelection(sender: UIButton) {
taskMgr.addTask(txt.text!, desc: txt1.text!, date: txt2.text!)
self.view.endEditing(true)
txt.text = ""
txt1.text = ""
txt2.text = "" // This is the data text
}
}
You could use UITableViewCellStyle.Value1 or UITableViewCellStyle.Value2 for your UITableViewCell style.
from Table View Styles and Accessory Views
UITableViewCellStyle.Value1 puts the subtitle in blue text and
right-aligns it on the right side of the row. Images are not
permitted.
While UITableViewCellStyle.Value2 puts the main title in blue and
right-aligns it at a point that’s indented from the left side of the
row. The subtitle is left aligned at a short distance to the right of
this point. This style does not allow images.
I have created a navigation menu with four item, now I want to link every item with a view controller, how I can do this?
I have used this tutorial: How to create navigation panel
CenterViewControllerDelegate:
#objc
protocol CenterViewControllerDelegate {
optional func toggleLeftPanel()
optional func collapseSidePanels()
}
class CenterViewController: UIViewController {
#IBOutlet weak private var imageView: UIImageView!
#IBOutlet weak private var titleLabel: UILabel!
#IBOutlet weak private var creatorLabel: UILabel!
var delegate: CenterViewControllerDelegate?
// MARK: Button actions
#IBAction func kittiesTapped(sender: AnyObject) {
delegate?.toggleLeftPanel?()
}
}
extension CenterViewController: SidePanelViewControllerDelegate {
func ItemMenuSelected(ItemMenu: Menu) {
imageView.image = ItemMenu.image
titleLabel.text = ItemMenu.title
creatorLabel.text = ItemMenu.creator
delegate?.collapseSidePanels?()
}
}
SidePanelViewControllerDelegate:
#objc
protocol SidePanelViewControllerDelegate {
func ItemMenuSelected(ItemMenu: Menu)
}
class SidePanelViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var delegate: SidePanelViewControllerDelegate?
var ItemMenus: Array<Menu>!
struct TableView {
struct CellIdentifiers {
static let MenuCell = "MenuCell"
}
}
func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
override func viewDidLoad() {
super.viewDidLoad()
var tblView = UIView(frame: CGRectZero)
tableView.tableFooterView = tblView
tableView.tableFooterView!.hidden = true
tableView.backgroundColor = UIColorFromRGB(0xE2F2C9)
tableView.reloadData()
}
}
// MARK: Table View Data Source
extension SidePanelViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ItemMenus.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(TableView.CellIdentifiers.MenuCell, forIndexPath: indexPath) as! MenuCell
cell.configureForMenu(ItemMenus[indexPath.row])
return cell
}
}
// Mark: Table View Delegate
extension SidePanelViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedMenu = ItemMenus[indexPath.row]
delegate?.ItemMenuSelected(selectedMenu)
}
}
class MenuCell: UITableViewCell {
#IBOutlet weak var ItemMenuImageView: UIImageView!
#IBOutlet weak var imageNameLabel: UILabel!
#IBOutlet weak var imageCreatorLabel: UILabel!
func configureForMenu(ItemMenu: Menu) {
ItemMenuImageView.image = ItemMenu.image
imageNameLabel.text = ItemMenu.title
imageCreatorLabel.text = ItemMenu.creator
}
}