View tableview cell text on table view cell button - ios

I have a table view where I have created a label and two buttons. I am stuck while getting the text from the label on button click. I have created an array list like:
let arrayList: [String] = [ "aaa" , "bbb" , "ccc"]
I want if I click the button on index[0] I shall get "aaa" and if index[2] I shall get "ccc"
#IBOutlet weak var titleLable: UILabel!
#IBOutlet weak var infoButton: UIButton!
myCell.titleLable.text = self.arrayList[indexPath.row]
myCell.infoButton.tag = indexPath.row
myCell.infoButton.addTarget(self, action: "buttonClicked", forControlEvents: .TouchUpInside)

Try to get indexPath, where the button is clicked using the Button Tag.
#IBAction func buttonClicked(sender:UIButton) {
let cell = tableView.cellForRowAtIndexPath(NSIndexPath.init(forRow: sender.tag, inSection: 0))
cell.myLabel.text = arrayList[sender.tag]
}

you need to do like
swift3
myCell.titleLable.text = self.arrayList[indexPath.row]
myCell.infoButton.tag = indexPath.row
myCell.infoButton.addTarget(self, action: #selector(yourVCName.buttonClicked(_:)), for: .touchUpInside)
get action as
#IBAction func buttonClicked(_ sender: UIButton){
print(self.arrayList[sender. tag])
}
Swift2
myCell.titleLable.text = self.arrayList[indexPath.row]
myCell.infoButton.tag = indexPath.row
myCell.infoButton.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)
#IBAction func buttonClicked(sender: UIButton){
print(self.arrayList[sender. tag])
}

In your Table View Controller
let dataSource: [String] = [ "aaa" , "bbb" , "ccc"]
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(YourCellIdentifier, forIndexPath: indexPath) as! YourCell
let title = dataSource[indexPath.row]
cell.setup(withTitle: title, delegate: self)
return cell
}
// MARK: - Your Cell Delegate
func didTapActionButton(fromCell cell: UITableViewCell) {
if let indexPath = itemTable.indexPathForCell(cell) {
let selectedItem = dataSource[indexPath.row]
print(selectedItem)
}
}
In your Table View Cell
Firstly, define a protocol:
protocol YourTableViewCellDelegate {
func didTapActionButton(fromCell cell: UITableViewCell)
}
And then:
// MARK: - Properties
var delegate: YourTableViewCellDelegate?
// MARK: - #IBOutlets
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var infoButton: UIButton!
// MARK: - #IBActions
#IBAction func buttonClicked(sender: UIButton) {
delegate?.didTapActionButton(fromCell: self)
}
// MARK: - Public Methods
func setup(withTitle title: title, delegate: YourTableViewCellDelegate?) {
titleLabel.text = title
self.delegate = delegate
}

Related

Table View Cell has no Initialiser

I am trying to display table view cell property into different table view cell when button I clicked . I am using story board . I added the Horizontal and vertical stack to contains the image and label properties . I want to display this property into another table view cell when user clicked the show button . In cellFor row function i defined the button action property . I am getting following error .Class 'DetailsViewCell' has no initializers. Cannot use instance member 'mc' within property initializer; property initializers run before 'self' is available
Here is the screenshot of the both view controller .
Here is the code .
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// guard let cell = tableView.dequeueReusableCell(withIdentifier: MovieCell.identifier, for: indexPath) as? MovieCell
// else { return UITableViewCell() }
let cell = tableView.dequeueReusableCell(withIdentifier: MovieViewCell.identifier, for: indexPath) as! MovieViewCell
cell.showButton.tag = indexPath.row
cell.showButton.addTarget(self, action: Selector("movieDetails"), for: .touchUpInside)
let row = indexPath.row
let title = presenter.getTitle(by: row)
let overview = presenter.getOverview(by: row)
let data = presenter.getImageData(by: row)
cell.configureCell(title: title, overview: overview, data: data)
return cell
}
}
Here is the code in identifier class with table view cell.
class MovieViewCell: UITableViewCell {
static let identifier = "MovieViewCell"
#IBOutlet weak var mainStackView: UIStackView!
#IBOutlet weak var movieImage: UIImageView!
#IBOutlet weak var movieTtile: UILabel!
#IBOutlet weak var movieOverview: UILabel!
#IBOutlet weak var showButton: UIButton!
#IBAction func movieDetails(_ sender: UIButton) {
var dc : DetailsViewCell
movieTtile = dc.movieTitle
movieOverview = dc.movieOverview
movieImage = dc.movieImage
}
func configureCell(title: String?, overview: String?, data: Data?) {
movieTtile.text = title
movieOverview.text = overview
if let imageData = data{
movieImage.image = UIImage(data: imageData)
}
}
}
Here is the code for Details view cell.
class DetailsViewCell: UITableViewCell {
#IBOutlet weak var movieTitle: UILabel!
#IBOutlet weak var movieOverview: UILabel!
#IBOutlet weak var movieImage: UIImageView!
var mc : MovieViewCell
movieTitle = mc.movieTtile
movieOverview = mc.movieOverview
movieImage = mc.movieImage
}
import UIKit
var loginData = ["", "", ""]
class LoginDataCell: UITableViewCell, UITextFieldDelegate {
#IBOutlet weak var txtLoginData: UILabel!
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
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.tag == 0 {
loginData[0] = textField.text
} else if textField.tag == 1 {
loginData[1] = textField.text
} else if textField.tag == 2 {
loginData[2] = textField.text
}
}
}

How to access the value of view controller into the tableview inside tableview in Swift

I am new in Swift and I am not able to access IBOutlet variable in tableview cell inside tableview cell.
My code is something like this.
In view controller:
#IBOutlet var lblPopupTitle: UILabel!
In Tableview Inside Cell:
cell.btnEdit.tag = indexPath.item
cell.btnEdit.addTarget(self, action: #selector(btnEdit), for: .touchUpInside)
In Tableview Cell:
class AttendanceInOutCell: UITableViewCell {
#IBOutlet var txtStartAt: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
}
#objc func btnEditClick(_ sender: UIButton)
{
let index = IndexPath(row: sender.tag, section: 0)
let cell: AttendanceInsideCell = tableAway.cellForRow(at: index) as! AttendanceInsideCell
lblPopupTitle.text = cell.txtAwayStart.text
}
}
lblPopupTitle show me "Use of unresolved identifier 'lblPopupTitle'". How can I solve this issue?
There are several ways to achieve this.
Protocol- Delegate approach:
protocol PassDataDelagate: class {
func passtextFieldText(_ startText: String)
}
Make a protocol in class:
AttendanceInOutCell: UITableViewCell {
#IBOutlet var txtStartAt: UITextField!
weak var textDelegate: PassDataDelagate?
override func awakeFromNib() {
super.awakeFromNib()
}
#objc func btnEditClick(_ sender: UIButton)
{
let index = IndexPath(row: sender.tag, section: 0)
let cell: AttendanceInsideCell = tableAway.cellForRow(at: index) as! AttendanceInsideCell
textDelegate?.passtextFieldText(cell.txtAwayStart.text)
}
}
Inside Tableview Cell, add this line:
cell.btnEdit.tag = indexPath.item
cell.textDelegate = self
cell.btnEdit.addTarget(self, action: #selector(btnEdit), for: .touchUpInside)
Add this in view controller:
func passtextFieldText(_ startText: String) {
lblPopupTitle.text = startText
}
P.S: You can also pass multiple information in the delegate function if you want.
protocol AttendanceDelegate: class {
func didTapOnBtn(_ popUpTitle: String)
}
class AttendanceInOutCell: UITableViewCell {
#IBOutlet var txtStartAt: UITextField!
weak var delegate: AttendanceDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
#objc func btnEditClick(_ sender: UIButton)
{
let index = IndexPath(row: sender.tag, section: 0)
let cell: AttendanceInsideCell = tableAway.cellForRow(at: index) as! AttendanceInsideCell //( I'm not getting this from where you get this tableAway variable) // So I m just telling you how you can set lblpopupTitle.text in viewController
lblPopupTitle.text = cell.txtAwayStart.text // remove this line
self.delegate.didTapOnBtn(cell.txtAwayStart.text) // please unwrap the textfield text before passing it as parameter
}
}
// for view controller
// there must be as tableview cellforRowAt function where you are creating your cell
// so after creating the cell instance
// add this line ( cell.delegate = self) and return cell
// now add extension to your controller
extension ViewController: AttendanceDelegate {
func didTapOnBtn(_ popUpTitle: String) {
lblPopupTitle.text = popUpTitle
}
}

Open URL with a button inside a table view cell

I want to include a button in each table cell that opens a URL.
I've created tables (using an array) with images and labels just fine, however I'm confused how to create a button
Here's what I have so far
class ExploreCell: UITableViewCell {
#IBOutlet weak var exploreImageView: UIImageView!
#IBOutlet weak var exploreTitleView: UILabel!
#IBOutlet weak var exploreDescriptionView: UILabel!
#IBOutlet weak var exploreButton: UIButton!
func setExplore(explore: Explore) {
exploreImageView.image = explore.image
exploreTitleView.text = explore.title
exploreDescriptionView.text = explore.description
exploreButton.addTarget(self, action: "connected:", for: .touchUpInside) = explore.button
}
My Class for the array looks like this
class ExploreListScreen: UIViewController {
#IBOutlet weak var tableView: UITableView!
var explores: [Explore] = []
override func viewDidLoad() {
super.viewDidLoad()
explores = createArray ()
tableView.delegate = self
tableView.dataSource = self
}
func createArray() -> [Explore] {
var tempExplores: [Explore] = []
let explore1 = Explore(image: #imageLiteral(resourceName: "test"), title: "Demo", description: "Essential", button: "")
tempExplores.append(explore1)
return tempExplores
}
Finally I have another file which contains the declared variables
class Explore {
var image: UIImage
var title: String
var description: String
var button: UIButton
init(image: UIImage, title: String, description: String, button: UIButton) {
self.image = image
self.title = title
self.description = description
self.button = button
}
Any advice and guidance would be fantastic. Thank-you!
Here's how I usually solve this. Create a delegate for your UITableViewCell subclass, and set the view controller owning the tableView as its delegate. Add methods for the interactions that happens inside the cell.
protocol YourTableViewCellDelegate: class {
func customCellDidPressUrlButton(_ yourTableCell: YourTableViewCell)
}
class YourTableViewCell: UITableViewCell {
weak var delegate: YourTableViewCellDelegate?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let button = UIButton()
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
addSubview(button)
}
required init?(coder _: NSCoder) {
return nil
}
#objc func buttonTapped() {
delegate?.customCellDidPressUrlButton(self)
}
}
Then, in the controller, set itself as a delegate and get the indexPath trough the proper method, indexPath(for:)
class YourTableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! YourTableViewCell
cell.delegate = self
return cell
}
}
extension YourTableViewController: YourTableViewCellDelegate {
func customCellDidPressUrlButton(_ yourTableCell: YourTableViewCell) {
guard let indexPath = tableView.indexPath(for: yourTableCell) else { return }
print("Link button pressed at \(indexPath)")
}
}
Then use that indexPath to grab the correct URL and present it from your table viewcontroller with a SFSafariViewController.
Swift 4
This is best way to get indexPath using touchPoint
class YourTableViewController: UITableViewController {
// ...
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SwiftyCell", for: indexPath) as! SwiftyTableViewCell
cell.label.text = "This is cell number \(indexPath.row)"
// WRONG! When cells get reused, these actions will get added again! That's not what we want.
// Of course, we could get around this by jumping through some hoops, but maybe there's a better solution...
cell.yourButton.addTarget(self, action: #selector(self.yourButtonTapped(_:)), for: .touchUpInside)
return cell
}
func yourButtonTapped(_ sender: Any?) {
let point = tableView.convert(sender.center, from: sender.superview!)
if let wantedIndexPath = tableView.indexPathForItem(at: point) {
let cell = tableView.cellForItem(at: wantedIndexPath) as! SwiftyCell
}
}
// ...
}
For more details you can follow this tutorials
Just create UIButton object in viewDidLoad and add this button as a sub view on cell in cellForRowAtIndexPath function. Take Burton's frame as per your requirement.

how to enable button when all textfields filled in tableviewcell(SWIFT)

I want to enable the button in the viewcontroller when I fill in the textfield in the tableviewcell.
I don't know how to solve the problem.
Sorry. I am immature in English.
button(viewController) isEnable = false
fill textfields(inside tableviewcell)
button(viewController) isEnable = true
1. ViewController
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
#IBOutlet var tableView: UITableView!
#IBOutlet var viewLabel: UILabel!
#IBOutlet var clickBtn: UIButton!
var cell: CustomTableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
self.clickBtn.isEnabled = false
cell.textFieldCell.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
cell.textFieldCell2.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
#objc func editingChanged(sender: UITextField) {
sender.text = sender.text?.trimmingCharacters(in: .whitespaces)
guard
let text1 = cell.textFieldCell.text, !text1.isEmpty,
let text2 = cell.textFieldCell2.text, !text2.isEmpty
else
{
self.clickBtn.isEnabled = false
return
}
clickBtn.isEnabled = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! CustomTableViewCell
return cell
}
}
2. CustomTableView
import UIKit
class CustomTableViewCell: UITableViewCell, UITextFieldDelegate {
#IBOutlet var myLabel: UILabel!
#IBOutlet var textFieldCell: UITextField!
#IBOutlet var textFieldCell2: UITextField!
}
As the table view contains only one cell why do you use a table view at all?
And if you really need to use a table view why don't you use a static cell?
A simple solution is to move the target/action code from viewDidLoad into the didSet property observer of the cell
var cell: CustomTableViewCell! {
didSet {
cell.textFieldCell.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
cell.textFieldCell2.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.clickBtn.isEnabled = false
}
One option is to use delegate.
protocol CustomTableViewCellDelegate {
func editingChanged(_ String: yourString)
}
In table view cell
class TableViewCell: UITaleViewCell {
// declare the delegate
var delegate: CustomTableViewCellDelegate?
// and pass it like this from where you want to pass
delegate?.editingChanged(cookie)
}
For using in tableViewController. first assign the delegate to self in cell for row at indexpath method. Then implement the delegate in it.
extension CustomTableViewController: CustomTableViewCellDelegate {
func editingChanged(String: yourString) {
// use it accordingly
}
}

How to alter a button in cell on click in swift ios?

I have a table layout inside a view which as a custom cell,The problem I'm facing is that the cells inside has a button i want to hide the button in cell on clicking it(only the one that is clicked should be hidden) how can i do thing in correct method?
ScrollCell.swift
class ScrollCell: UITableViewCell {
#IBOutlet weak var ProfilePic: SpringImageView!
#IBOutlet weak var UserName: SpringButton!
#IBOutlet weak var Closet: UILabel!
#IBOutlet weak var Style: UILabel!
//------//
#IBOutlet weak var MianImg: UIImageView!
//-------//
#IBOutlet weak var ProductName: UILabel!
#IBOutlet weak var LoveCount: UIButton!
#IBOutlet weak var Discount: UILabel!
#IBOutlet weak var OrginalPrice: UILabel!
#IBOutlet weak var Unliked: UIButton!
#IBOutlet weak var Liked: UIButton!
#IBOutlet weak var Comment: UIButton!
#IBOutlet weak var Share: SpringButton!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func layoutSubviews() {
ProfilePic.layer.cornerRadius = ProfilePic.bounds.height / 2
ProfilePic.clipsToBounds = true
}
}
ScrollController.swift
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1 // however many sections you need
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(try! Realm().objects(Feed))
var FeedModel = Feed()
let realm = try! Realm()
let tan = try! Realm().objects(Feed).sorted("ID", ascending: false)
return tan.count // however many rows you need
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// get an instance of your cell
cell = tableView.dequeueReusableCellWithIdentifier("ScrollCellDqueue", forIndexPath: indexPath) as! ScrollCell
IndexPath = indexPath.row
var FeedModel = Feed()
let realm = try! Realm()
let tan = try! Realm().objects(Feed).sorted("ID", ascending: false)
cell.ProfilePic.kf_setImageWithURL(NSURL(string:tan[indexPath.row].ProfilePic)!)
cell.UserName.setTitle(tan[indexPath.row].FullName, forState: .Normal)
cell.Style.text = tan[indexPath.row].StyleType
if tan[indexPath.row].UserType == "store_front"{
cell.Closet.text = "Store Front"
}else if tan[indexPath.row].UserType == "normal"{
cell.Closet.text = "Pri Loved"
}
//-----//
var SingleImage:String = ""
var ImageArray = tan[indexPath.row].ImageArraySet.componentsSeparatedByString(",")
SingleImage = ImageArray[0]
cell.MianImg.kf_setImageWithURL(NSURL(string:SingleImage)!)
//-----//
cell.ProductName.text = tan[indexPath.row].ItemName
cell.OrginalPrice?.text = "\(tan[indexPath.row].OrginalPrice)"
cell.LoveCount.setTitle("\(tan[indexPath.row].LikeCount)"+" Loves", forState: .Normal)
cell.Discount.text = "\(tan[indexPath.row].Discount)"+" % off"
if(tan[indexPath.row].LikeStatus){
cell.Unliked.hidden = true
cell.Liked.hidden = false
}
else if (!tan[indexPath.row].LikeStatus){
cell.Unliked.hidden = false
cell.Liked.hidden = true
}
cell.Unliked.tag = tan[indexPath.row].ID
cell.Liked.tag = tan[indexPath.row].ID
return cell
}
#IBAction func LikeBtn(sender: AnyObject) {
print(sender.tag)
print(IndexPath)
//here i want to know who i can hide the button i have clicked ?
}
Here i want to access the cell in which button is clicked and make changes to UI item inside that cell how can i do that ?
There are many ways to do it. One possible solution is use block.
Add this to ScrollCell
var didLikedTapped: (() -> Void)?
and receive the event of the LikedButton in the cell
#IBAction func LikeBtn(sender: AnyObject) {
didLikedTapped?()
}
Then in cellForRowAtIndexPath of viewController add this
cell.didLikedTapped = {[weak self] in
print(IndexPath)
}
Liked is uibutton in ScrollCell, i don't known, why can you add IBAction for it in ScrollController? . You must implement it in ScrollCell And code:
#IBAction func LikeBtn(sender: UIButton) {
print(sender.tag)
sender.hiden = true
}
And i think, if you have only one UIbutton, it will better. In there, like and unlike is 2 state of uibutton(seleted and none). When you click the button, change it's state
Update:
class sampleCell: UITableViewCell{
#IBOutlet var btnLike : UIButton!
#IBOutlet var btnUnLike : UIButton! // frame of 2 button is equal
override func awakeFromNib() {
super.awakeFromNib()
self.btnUnLike.hidden = true
// ...
}
func updateData(data:AnyObject){ // data's type is Feed
// set data for cell
// i think you should implement in here. and in ScollController call : cell.updateData() , it's better
/* e.x
self.ProductName.text = tan[indexPath.row].ItemName
self.OrginalPrice?.text = "\(tan[indexPath.row].OrginalPrice)"
self.LoveCount.setTitle("\(tan[indexPath.row].LikeCount)"+" Loves", forState: .Normal)
self.Discount.text = "\(tan[indexPath.row].Discount)"+" % off"
*/
}
#IBAction func likeTap(sender:UIButton){ // rememeber set outlet event for btnLike and btnUnLike is this function
if sender == self.btnLike{
self.btnLike.hidden = true
self.btnUnLike.hidden = false
// do s.t
}else if sender == self.btnUnLike{
self.btnLike.hidden = false
self.btnUnLike.hidden = true
// do s.t
}
}
}
Check if the following code help
#IBAction func LikeBtn(sender: AnyObject) {
var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(position)
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
UITableViewCell
print(indexPath?.row)
}
give the LikeBtn the property indexpath, in cellForRowAtIndexPath method, pass the indexPath to the LikeBtn, then you will know which cell's LikeBtn clicked.
class LikeBtn: UIButton {
var indexPath: NSIndexPath?
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// here pass the indexpath to your button
cell.likeBtn.indexPath = indexPath
return cell
}
#IBAction func likeTap(sender: LikeBtn){
if let indexPath = sender.indexPath {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
//here you will know the exact cell, now you can hide or show your buttons
}
}
}

Resources