I have UITableViewCell with UITextView and UIView
I'm try to hide/show UIView
Constraints — TextView:
Trailing to Superview Equals 2
Leading to Superview Equals 2
Top to Superview Equals 2
Bottom to Superview Equals 40
UIVIew:
Trailing to Superview
Leading to Superview
Bottom to Superview
Height 35
In Cell class I'm connect TextView BottomConstraint
UITableViewCell class :
#IBOutlet weak var myTextView: UITextView!
#IBOutlet weak var detailView: UIView!
#IBOutlet weak var detailLabel: UILabel!
#IBOutlet weak var TextViewConstraintToBottom: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
detailView.isHidden = true
if detailView.isHidden == true {
TextViewConstraintToBottom.constant = 0
} else {
TextViewConstraintToBottom.constant = 40
}
}
In ViewController with UITableView :
var handle: DatabaseHandle?
var ref: DatabaseReference?
var quoteList: [String] = []
var songArray: [String] = []
override func viewWillAppear(_ animated: Bool) {
myTableView.estimatedRowHeight = 100
myTableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidLoad() {
super.viewDidLoad()
myTableView.dataSource = self
myTableView.delegate = self
dataCatch()
}
func dataCatch() {
ref = Database.database().reference()
handle = ref?.child("Цитаты").child("\(cat)").child("\(quoteNAme)").observe(.childAdded, with: { (snapshot) in
let username = snapshot.value as? NSDictionary
if let us = username?["name"] {
self.quoteList.append(us as! String)
self.quoteList = self.quoteList.filter(){$0 != "1"}
self.myTableView.reloadData()
}
if let us = username?["song"].unsafelyUnwrapped {
self.celT?.detailView.isHidden = false
self.songArray.append(us as! String)
self.myTableView.reloadData()
}
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuoteTableVC
let indexP = indexPath.row
cell.myTextView.text = quoteList[indexP]
cell.detailLabel.text = songArray[indexP]
return cell
}
In database I have structure
I decided
In ViewController :
func dataCatch() {
ref = Database.database().reference()
handle = ref?.child("Цитаты").child("\(cat)").child("\(quoteNAme)").observe(.childAdded, with: { (snapshot) in
let username = snapshot.value as? NSDictionary
if let us = username?["name"] {
self.quoteList.append(us as! String)
self.quoteList = self.quoteList.filter(){$0 != "1"}
self.myTableView.reloadData()
}
if snapshot.hasChild("song") {
let us = username?["song"]
self.songArray.append(us as! String)
} else {
let tet = "1"
// self.celT?.detailView.isHidden = true
self.songArray.append(tet as! String)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.detailLabel.text = songArray[indexP]
if cell.detailLabel.text != "1" {
cell.detailView.isHidden = false
cell.butConstraint.constant = 40
} else {
cell.detailView.isHidden = true
cell.butConstraint.constant = 0
}
In cellForRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UI TableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuoteTableVC
// hide = check your model whether it has song or not
if hide {
cell.TextViewConstraintToBottom.constant = 0
}
else {
cell.TextViewConstraintToBottom.constant = 40
}
}
Related
`Hello!
I have a tableview and 2 arrays.
When I switch between tabs the tableview reloads. In the first tab, I click on favorites, change the color and add the data to another array. When switching to the second tab, the color does not change. how can i implement this?
MyCell
protocol CellSubclassDelegate: class {
func gestureTapped(cell: StocksCell)
}
class StocksCell: UITableViewCell {
#IBOutlet weak var logoImageView: UIImageView!
#IBOutlet weak var tickerLabel: UILabel!
#IBOutlet weak var favouriteImageView: UIImageView!{ didSet {
let panGesture = UITapGestureRecognizer(target: self, action: #selector(tapToAddFavourite))
favouriteImageView.addGestureRecognizer(panGesture)
favouriteImageView.isUserInteractionEnabled = true
}
}
#IBOutlet weak var companyNameLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
#IBOutlet weak var deltaLabel: UILabel!
var selectedCell = false
weak var delegate: CellSubclassDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
#objc private func tapToAddFavourite(_ recognizer: UITapGestureRecognizer) {
guard recognizer.state == .ended else { return }
if selectedCell{
favouriteImageView.tintColor = UIColor.lightGray
selectedCell = false
}else{
favouriteImageView.tintColor = UIColor.yellow
selectedCell = true
}
self.delegate?.gestureTapped(cell: self)
}
}
MyController
class StocksViewController: UIViewController, CellSubclassDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var stocksLabel: UILabel! { didSet {
let tapGestureStocks = UITapGestureRecognizer(target: self, action: #selector(tapToStocks))
stocksLabel.addGestureRecognizer(tapGestureStocks)
stocksLabel.isUserInteractionEnabled = true
}
}
#IBOutlet weak var favouriteLabel: UILabel!{ didSet {
let tapGestureFavourite = UITapGestureRecognizer(target: self, action: #selector(tapToFavourite))
favouriteLabel.addGestureRecognizer(tapGestureFavourite)
favouriteLabel.isUserInteractionEnabled = true
}
}
fileprivate var stocksData = [StocksModel(n: "VNDX", f: "Vandex, LLC", t: "4 764,6 ₽", tt: "+55 ₽ (1,15%)"), StocksModel(n: "DDD", f: "Dandex, LLC", t: "1 764,6 ₽", tt: "+155 ₽ (1,15%)")]
var favouriteData = [StocksModel]()
let privateIdentifire = "StocksCell"
var isStocksSelected = true
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
#objc private func tapToFavourite(_ recognizer: UITapGestureRecognizer) {
guard recognizer.state == .ended else { return }
favouriteLabel.alpha = 1
favouriteLabel.font = favouriteLabel.font.withSize(28)
stocksLabel.alpha = 0.65
stocksLabel.font = stocksLabel.font.withSize(18)
stocksLabel.textAlignment = .center
isStocksSelected = false
tableView.reloadData()
}
#objc private func tapToStocks(_ recognizer: UITapGestureRecognizer) {
guard recognizer.state == .ended else { return }
favouriteLabel.alpha = 0.65
favouriteLabel.font = favouriteLabel.font.withSize(18)
stocksLabel.alpha = 1
stocksLabel.font = stocksLabel.font.withSize(28)
stocksLabel.textAlignment = .left
isStocksSelected = true
tableView.reloadData()
}
}
TABLEVIEW DATASOURCE
extension StocksViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let result = isStocksSelected ? stocksData.count : favouriteData.count
return result
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: privateIdentifire, for: indexPath) as! StocksCell
cell.delegate = self
if isStocksSelected{
cell.tickerLabel.text = stocksData[indexPath.row].name
cell.companyNameLabel.text = stocksData[indexPath.row].fullname
cell.priceLabel.text = stocksData[indexPath.row].ticker
cell.deltaLabel.text = stocksData[indexPath.row].tq
}else{
cell.tickerLabel.text = favouriteData[indexPath.row].name
cell.companyNameLabel.text = favouriteData[indexPath.row].fullname
cell.priceLabel.text = favouriteData[indexPath.row].ticker
cell.deltaLabel.text = favouriteData[indexPath.row].tq
}
return cell
}
func gestureTapped(cell: StocksCell) {
guard let indexPath = self.tableView.indexPath(for: cell) else {return}
if cell.selectedCell{
let dataStock = stocksData[indexPath.row]
favouriteData.append(dataStock)
}else{
favouriteData.remove(at: indexPath.row)
}
}
}
TABLEVIEW DELEGATE
extension StocksViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 68
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.layer.cornerRadius = 16
}
}
Change the color here:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: privateIdentifire, for: indexPath) as! StocksCell
cell.delegate = self
if isStocksSelected{
favouriteImageView.tintColor = UIColor.lightGray
cell.tickerLabel.text = stocksData[indexPath.row].name
cell.companyNameLabel.text = stocksData[indexPath.row].fullname
cell.priceLabel.text = stocksData[indexPath.row].ticker
cell.deltaLabel.text = stocksData[indexPath.row].tq
}else{
favouriteImageView.tintColor = UIColor.yellow
cell.tickerLabel.text = favouriteData[indexPath.row].name
cell.companyNameLabel.text = favouriteData[indexPath.row].fullname
cell.priceLabel.text = favouriteData[indexPath.row].ticker
cell.deltaLabel.text = favouriteData[indexPath.row].tq
}
return cell
}
i already parsed other values but how will i show image to imageView i m already using SdWebImage in Swift.I want to show that in Bottom cell "detail" Below is my code
import UIKit
import SystemConfiguration
import MBProgressHUD
public struct Section {
var arrayDataTop: String
var arrayTerms: String
var qrImage:String
var collapsed: Bool
public init( arrayDataTop: String,qrImage: String ,arrayTerms: String, collapsed: Bool = false) {
self.arrayDataTop = arrayDataTop
self.qrImage = qrImage
self.arrayTerms = arrayTerms
self.collapsed = collapsed
}
}
class CollapsibleViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tableViewCollapsible:UITableView!
#IBOutlet weak var listImage:UIImageView!
var nodatastr:String = "No Deal Found."
var dealIDCollapsible : String?
var dealDictCollapsible = [String: AnyObject]()
var parentNavigationController: UINavigationController?
private var loadingView:MBProgressHUD?
var sectionDataObj = [Section]()
override func viewDidLoad() {
super.viewDidLoad()
if (!self.isInternetAvailable()){
self.alertMessageShow(title: "No Internet Connection", message: "Make sure your device is connected to the internet.")
}
else{
if self.loadingView == nil {
self.loadingView = MBProgressHUD.showAdded(to: self.view, animated: true)
}
tableViewCollapsible.estimatedRowHeight = 100.0
tableViewCollapsible.layoutIfNeeded()
tableViewCollapsible.updateConstraintsIfNeeded()
tableViewCollapsible.tableFooterView = UIView()
self.listImageFetch()
dealFetchParticularListing()
}
}
func dealFetchParticularListing(){
let prs = [
"listing_id":dealIDCollapsible,//dealIDCollapsible,
"Deal_fetch_listing": "1" as String
]
Service.CreateDeal(prs as [String : AnyObject]?, onCompletion: { result in
let json = result as? NSDictionary
if let data = json as? [String:Any]{
if let err = data["status"] as? String, err == "success"{
if let data = data["result"] as? [Any]{
//
//fill your data in that local Section obj
//
var sectionDataObj = [Section]()
for sectionObj in data{
if let sectionObjVal = sectionObj as? [String:Any]{
if let qrcode = sectionObjVal["qrcode"] as? String{
if let tnc = sectionObjVal["tnc"] as? String{
if let deal_title = sectionObjVal["deal_title"] as? String{
let sectionValue = Section(arrayDataTop: deal_title, qrImage: qrcode, arrayTerms: tnc)
// access main objects/UIelement on main thread ONLY
sectionDataObj.append(sectionValue)
}
}
}
}
}
DispatchQueue.main.async { () -> Void in
self.sectionDataObj.removeAll()
//
//assign ur data in main sampleData(Section obj) then reload tableView with that data.
//
self.sectionDataObj = sectionDataObj
self.tableViewCollapsible.reloadData()
self.loadingView?.hide(true)
}
}
}
}
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Header
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyCellData
cell.lblDealTitle.text = sectionDataObj[indexPath.section].arrayDataTop
return cell
}
// Cell
let cell = tableView.dequeueReusableCell(withIdentifier: "detail") as! MyCellData
cell.lblTerm.text = sectionDataObj[indexPath.section].arrayTerms
// here i want to show image
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension//320.0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
let collapsed = !sectionDataObj[indexPath.section].collapsed
// Toggle collapse
sectionDataObj[indexPath.section].collapsed = collapsed
self.tableViewCollapsible.reloadSections([indexPath.section], with: .automatic)
}
}
}
class MyCellData:UITableViewCell{
#IBOutlet weak var lblDealTitle: UILabel!
#IBOutlet weak var dealimage: UIImageView!
#IBOutlet weak var lblTerm: UILabel!
#IBOutlet weak var qrCodeImage: UIImageView!
}
Plz help me with this.thanks in advance.All things are working properly i am able to see other details.Help will be appreciated.Plz help me i m struggling with this issue.
update ur tableView cellForRowAt like so to show an image or ur cell from ur sectionDataObj
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Header
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyCellData
cell.lblDealTitle.text = sectionDataObj[indexPath.section].arrayDataTop
return cell
}
// Cell
let cell = tableView.dequeueReusableCell(withIdentifier: "detail") as! MyCellData
cell.lblTerm.text = sectionDataObj[indexPath.section].arrayTerms
let imgUrl = sectionDataObj[indexPath.section]. qrImage
cell.qrCodeImage.sd_setImage(with: URL(string:imgUrl), completed: nil)
return cell
}
would love to pass the value postArray[indexpath.row].creatorId when the label inside a tableview cell is tapped so it can be passed onto the next view controller so i can load the profile of that particular creator/user. I used custom cells, so how do i get the creator id based on the location of the label(username) selected.
//custom cell
class PostCell : UITableViewCell
{
#IBOutlet weak var timeAgoLabel: UILabel!
#IBOutlet weak var usernameLabel: UILabel!
#IBOutlet weak var profileImageView: UIImageView!
#IBOutlet weak var postImageView: UIImageView!
#IBOutlet weak var captionLabel: UILabel!
#IBOutlet weak var postStatsLabel: UILabel!
}
//do something when label is tapped
#objc func tapFunction(sender:UITapGestureRecognizer) {
//userClicked = creatorData
print(userClicked)
appDelegate.profileView()
print("tap working")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return 1
}else{
return postsArray.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//var returnCell: UITableViewCell!
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "statusCell", for: indexPath) as! statusCell
profilePicture = UserDefaults.standard.object(forKey: "userPic") as? String
if profilePicture != nil {
//load profile picture from library
let urlString = "https://test.com/uploads/profile-picture/"+(profilePicture)!
let profileURL = URL(string: urlString)
cell.statusProfilePic?.downloadedFrom(url: profileURL!)
} else {
print("you have no profile picture set")
}
return cell
} else {
if postsArray[indexPath.row].photos != nil{
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
if postsArray[indexPath.row].comments != nil {
comments = postsArray[indexPath.row].comments?.count
} else {
comments = 0
}
if postsArray[indexPath.row].like_list != nil {
likes = postsArray[indexPath.row].like_list?.count
}else{
likes = 0
}
//assign post id to PostID
postID = postsArray[indexPath.row].post_id
//make username clickable!
let tap = UITapGestureRecognizer(target: self, action: #selector(NewsfeedTableViewController.tapFunction))
cell.usernameLabel.isUserInteractionEnabled = true
cell.usernameLabel.addGestureRecognizer(tap)
cell.usernameLabel.text = postsArray[indexPath.row].fullname
cell.timeAgoLabel.text = postsArray[indexPath.row].data_created
cell.captionLabel.text = postsArray[indexPath.row].content
cell.timeAgoLabel.text = postsArray[indexPath.row].modified
//15 Likes 30 Comments 500 Shares
cell.postStatsLabel.text = "\(likes!) Likes \(comments!) Comments"
//load profile picture from library
let urlString = "https://test.com/uploads/profile-picture/"+(postsArray[indexPath.row].profile_pic_filename)!
let profileURL = URL(string: urlString)
cell.profileImageView.downloadedFrom(url: profileURL!)
//iterate through posts images images array
//load post picture from server library
var postImageName : String?
if postsArray[indexPath.row].photos != nil{
let postImage = postsArray[indexPath.row].photos
for postsImage in postImage!{
postImageName = postsImage.filename!
}
let urlPostImageString = "https://test.com/uploads/post-picture/"+(postImageName)!
let postsImageUrl = URL(string: urlPostImageString)
cell.postImageView.downloadedFrom(url: postsImageUrl!)
} else {
print("Post has no picture")
}
//return cell
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "NoImageCell", for: indexPath) as! NoImageTableViewCell
if postsArray[indexPath.row].comments != nil {
comments = postsArray[indexPath.row].comments?.count
} else {
comments = 0
}
if postsArray[indexPath.row].like_list != nil {
likes = postsArray[indexPath.row].like_list?.count
} else {
likes = 0
}
//make username clickable!
let tap = UITapGestureRecognizer(target: self, action: #selector(NewsfeedTableViewController.tapFunction))
cell.noImageUsername.isUserInteractionEnabled = true
cell.noImageUsername.addGestureRecognizer(tap)
cell.noImageUsername.text = postsArray[indexPath.row].fullname
cell.noImageTime.text = postsArray[indexPath.row].data_created
cell.noImagePost.text = postsArray[indexPath.row].content
cell.noImageTime.text = postsArray[indexPath.row].modified
//15 Likes 30 Comments 500 Shares
cell.noImageLikeAndComment.text = "\(likes!) Likes \(comments!) Comments"
//load profile picture from library
let urlString = "https://test.com/uploads/profile-picture/"+(postsArray[indexPath.row].profile_pic_filename)!
let profileURL = URL(string: urlString)
cell.noImageProfilePic.downloadedFrom(url: profileURL!)
return cell
}
}
}
Use this for example.
Implement didSelectRow() method and in it write something like this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// this method works, when you taped cell. write here code of you need. Next code only example, which set user info to some VC and push it:
let controller = UserController as? UserController
if let controller = controller {
controller.user = users[indexPath.row]
self.navigationController?.pushViewController(controller, animated: true)
}
}
add this to your Cell's class:
func setTap() {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapRecognized))
self.label.addGestureRecognizer(tap)
tap.numberOfTapsRequired = 1
}
#objc func tapRecognized(sender: UITapGestureRecognizer) {
// here your code of tap on label
print("label tapped")
}
Check on storyBoard is your label isUserInteractionEnabled? - set it to true. Inside tapRecodnized() method do what are you need. And you need to call method setTap() in your cell's method, which you call in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell.
Update
Simple example. this code know what are you tapped. if you tap cell, but not label, add code of push some controller, else code of push another controller.
Cell's Class:
class MyTableViewCell: UITableViewCell {
#IBOutlet weak var label: UILabel!
var mainController: ViewController?
func setText(text: String) {
setTap()
label.text = text
}
func setTap() {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapRecognized))
self.label.addGestureRecognizer(tap)
tap.numberOfTapsRequired = 1
}
#objc func tapRecognized(sender: UITapGestureRecognizer) {
if let mainController = mainController {
print("label tapped")
mainController.pushSomeVc(cell: self)
}
}
}
Code of main Class:
class ViewController: UIViewController {
#IBOutlet weak var myTableView: UITableView!
var array = ["1", "2", "3", "4", "5", "6"]
override func viewDidLoad() {
super.viewDidLoad()
}
func pushSomeVc(cell: MyTableViewCell) {
let row = myTableView.indexPath(for: cell)?.row
if let row = row {
// write here code of push controller, when label tapped. row property for get some user from array
print("push some vc with \(row)")
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCell(withIdentifier: "cell") as? MyTableViewCell
if let cell = cell {
cell.setText(text: array[indexPath.row])
cell.mainController = self
}
return cell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
// write here code of push controller with comments
print("cell tapped: \(indexPath.row)")
}
}
I tested this code and it's work perfect
I'm trying to send a request to search for movies, but when i tap on the search bar to write the text i get a crash in cellforrow and it's not calling numberofrows neither the request. Here's my code so far:
class InTheaters: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
#IBOutlet weak var poster: UIImageView!
#IBOutlet weak var movieTitle: UILabel!
#IBOutlet weak var date: UILabel!
#IBOutlet weak var duration: UILabel!
#IBOutlet weak var rating: UILabel!
#IBOutlet var theatersTable: UITableView!
#IBOutlet weak var starsView: CosmosView!
var results = [Movie]()
var searchResults = [Search]()
var resultSearchController: UISearchController!
private let key = "qtqep7qydngcc7grk4r4hyd9"
override func viewDidLoad() {
super.viewDidLoad()
self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController.searchResultsUpdater = self
self.resultSearchController.dimsBackgroundDuringPresentation = false
self.resultSearchController.searchBar.sizeToFit()
self.resultSearchController.searchBar.placeholder = "Search for movies"
self.theatersTable.tableHeaderView = self.resultSearchController.searchBar
self.theatersTable.reloadData()
getMovieInfo()
customIndicator()
infiniteScroll()
}
func customIndicator() {
self.theatersTable.infiniteScrollIndicatorView = CustomInfiniteIndicator(frame: CGRectMake(0, 0, 24, 24))
self.theatersTable.infiniteScrollIndicatorMargin = 40
}
func infiniteScroll() {
self.theatersTable.infiniteScrollIndicatorStyle = .White
self.theatersTable.addInfiniteScrollWithHandler { (scrollView) -> Void in
self.getMovieInfo()
}
}
func getMovieInfo() {
Alamofire.request(.GET, "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json?page_limit=10&page=1&country=us&apikey=\(key)").responseJSON() {
(responseData) -> Void in
if let swiftyResponse = responseData.result.value {
let movies = Movies(JSONDecoder(swiftyResponse))
for movie in movies.allMovies {
self.results.append(movie)
}
}
self.theatersTable.reloadData()
self.theatersTable.finishInfiniteScroll()
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.searchResults.removeAll(keepCapacity: false)
if (searchController.searchBar.text?.characters.count > 0) {
Alamofire.request(.GET, "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=N&page_limit=10&page=1&apikey=\(key)").responseJSON() {
(responseData) -> Void in
print(responseData)
if let swiftyResponse = responseData.result.value {
let searches = Searches(JSONDecoder(swiftyResponse))
for search in searches.allSearches {
self.searchResults.append(search)
}
}
self.theatersTable.reloadData()
self.theatersTable.finishInfiniteScroll()
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.resultSearchController.active) {
return self.searchResults.count
} else {
return self.results.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
let titleLabel = cell.viewWithTag(1) as! UILabel
let yearLabel = cell.viewWithTag(2) as! UILabel
let durationLabel = cell.viewWithTag(3) as! UILabel
let posterImage = cell.viewWithTag(5) as! UIImageView
let starsTag = cell.viewWithTag(6) as! CosmosView
if (self.resultSearchController.active) {
titleLabel.text = searchResults[indexPath.row].titleMovie
yearLabel.text = searchResults[indexPath.row].yearMovie
durationLabel.text = searchResults[indexPath.row].durationMovie?.description
posterImage.sd_setImageWithURL(NSURL(string: searchResults[indexPath.row].posterMovie!))
starsTag.rating = searchResults[indexPath.row].ratingMovie!
starsTag.settings.updateOnTouch = false
} else {
titleLabel.text = results[indexPath.row].titleMovie
yearLabel.text = results[indexPath.row].yearMovie
durationLabel.text = results[indexPath.row].durationMovie?.description
posterImage.sd_setImageWithURL(NSURL(string: results[indexPath.row].posterMovie!))
starsTag.rating = results[indexPath.row].ratingMovie!
starsTag.settings.updateOnTouch = false
}
return cell
}
I also have some structs with information for the request tell me if you need something from that too.
Found the answer should have reloadData before the request.
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.searchResults.removeAll(keepCapacity: false)
self.theatersTable.reloadData()//should have added this before the request
if (searchController.searchBar.text?.characters.count > 0) {
Alamofire.request(.GET, "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=\(searchController.searchBar.text!)&page_limit=10&page=1&apikey=\(key)").responseJSON() {
(responseData) -> Void in
if let swiftyResponse = responseData.result.value {
let searches = Searches(JSONDecoder(swiftyResponse))
for search in searches.allSearches {
self.searchResults.append(search)
}
}
self.theatersTable.reloadData()
self.theatersTable.finishInfiniteScroll()
}
}
}
I would like to create dynamic height of UITableViewCell depending tablecell content.
But i couldn't.
import UIKit
class WorkItemCell: UITableViewCell{
#IBOutlet weak var item_view: UIView!
#IBOutlet weak var minimum_startday_label: CustomLabel!
#IBOutlet weak var catchcopyLabel: CustomLabel!
#IBOutlet weak var stationLabel: UILabel!
#IBOutlet weak var paymentLabel: UILabel!
#IBOutlet weak var limitLabel: UILabel!
#IBOutlet weak var mainjobLabel: UILabel!
#IBOutlet weak var companyLabel: UILabel!
#IBOutlet weak var workstartdateLabel2: UILabel!
#IBOutlet weak var fav_view: ImageWithView!
#IBOutlet weak var img_seen_view: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
//self.fav_view = ImageWithView.instance()
self.fav_view.checkedImage = UIImage(named: "fav_on")
self.fav_view.uncheckedImage = UIImage(named: "fav_off")
}
override func layoutSubviews() {
super.layoutSubviews()
self.contentView.layoutIfNeeded()
self.catchcopyLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.catchcopyLabel.bounds)
}
private var _workdic: NSDictionary?
var workdic: NSDictionary? {
get {
return _workdic
}
set(workdic) {
_workdic = workdic
if let workdic = workdic {
let workplace = workdic["WorkPlace"] as? String
let companyname = workdic["CompanyName"] as? String
let jobname = workdic["JobName"] as? String
let payment = workdic["Payment"] as? String
let workstartdate = workdic["WorkStartDate"] as? String
let workdatetime = workdic["WorkDateTime"] as? String
let minimumday = workdic["MinimumWorkDay"] as? String
let applyenddate = workdic["ApplyEndDate"] as? String
let catchcopy = workdic["CatchCopy"] as? String
if notnullCheck(catchcopy){
//行間
let attributedText = NSMutableAttributedString(string: catchcopy!)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedText.length))
self.catchcopyLabel.attributedText = attributedText
}
self.catchcopyLabel.sizeToFit()
if let payment_constant = payment{
self.paymentLabel.text = payment_constant
}
if notnullCheck(minimumday) && notnullCheck(workstartdate){
self.minimum_startday_label.text = minimumday!+" "+workstartdate!
}else{
self.minimum_startday_label.text = ""
}
if let applyenddate_constant = applyenddate{
self.limitLabel.text = applyenddate_constant
}
if let jobname_constant = jobname{
self.mainjobLabel.text = jobname_constant
}
if let workdatetime_constant = workdatetime{
self.workstartdateLabel2.text = workdatetime_constant
}
if let companyname_constant = companyname{
self.companyLabel.text = companyname_constant
}
self.stationLabel.text = workplace
self.item_view.sizeToFit()
}
}
}
class func heightForRow(tableView: UITableView, workdic: NSDictionary?) -> CGFloat {
struct Sizing {
static var cell: WorkItemCell?
}
if Sizing.cell == nil {
Sizing.cell = tableView.dequeueReusableCellWithIdentifier("WorkItemCell") as? WorkItemCell
}
if let cell = Sizing.cell {
cell.frame.size.width = CGRectGetWidth(tableView.bounds)
cell.workdic = workdic
cell.setNeedsDisplay()
cell.layoutIfNeeded()
let size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
print(size)
return size.height+1
}
return 0
}
}
Above code has item_view.
It has all label and image.
It is setted margin at 4 points(top,left,bottom,right),5px.
I use above cell for data list.
It has around 5000 counts.
Catch copy label is often setted 2 line sentence.
I want to change item_view height and cell height each catch_copy_label's height.
But I couldn't.
I always have gotten same height,26px.
(366.5, 26.0)
(366.5, 26.0)
What should i do?
I have add the part of view controller's source.
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
if self.int_total == 0{
return self.view.frame.size.height
}else{
if let workdic: AnyObject = workdata.safeObjectAtIndex(indexPath.row){
return WorkItemCell.heightForRow(self.workview, workdic: (workdic as! NSDictionary),base_height:170)
}else{
return 199
}
}
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 199
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.int_total == 0{
return 1
}
return self.workdata.count
}
/*
Cellに値を設定する.
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Cellの.を取得する.
if self.int_total > 0{
let cell = workItemCell(tableView, cellForRowAtIndexPath: indexPath, str_xib: "WorkItemCell")
return cell
}else{
let nocell: NoCountCell = tableView.dequeueReusableCellWithIdentifier("NoCountCell", forIndexPath: indexPath) as! NoCountCell
nocell.conditionButton.addTarget(self, action: "onClickBack:", forControlEvents: .TouchUpInside)
//初期が終わったらfalse
if self.init_loading{
nocell.conditionButton.hidden = true
nocell.messageLabel.hidden = true
}else{
nocell.conditionButton.hidden = true
nocell.messageLabel.hidden = false
}
return nocell
}
}
func workItemCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath,str_xib:String) ->WorkItemCell{
let wcell: WorkItemCell = tableView.dequeueReusableCellWithIdentifier(str_xib, forIndexPath: indexPath) as! WorkItemCell
wcell.separatorInset = UIEdgeInsetsZero
wcell.selectionStyle = UITableViewCellSelectionStyle.None
updateCell(wcell, atIndexPath: indexPath)
return wcell
}
func updateCell(cell:UITableViewCell,atIndexPath:NSIndexPath){
}
func showWorkItem(wcell:WorkItemCell,workdic:NSDictionary){
wcell.workdic = workdic
}
I have posted capture.
This is in Objective C.Calculate the height of cell's content in heightForRowAtIndexPath method add it in one array as
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
text =[NSString stringWithFormat:#"%#",[content_array objectAtIndex:indexPath.row]];
CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tblView.frame.size.width - PADDING * 3, 1000.0f)];
NSLog(#"%f",textSize.height);
[height_Array addObject:[NSString stringWithFormat:#"%f", textSize.height]];
return textSize.height;
}
Now in cellForRowAtIndexPath method set the frame of title using height array as:-
CGRect newFrame = txtTitle.frame;
newFrame.size.height = [[height_Array objectAtIndex:indexPath.row] floatValue];
txtTitle.frame = newFrame;
I finaly got answer.
But i have calculated height manually.
I calculated the label's height at each time.
This label has multi line.
Then I set height other height + the height which was calcuted.
class func heightForCatchCopy(tableView: UITableView, workdic: NSDictionary?) -> CGFloat {
struct Sizing {
static var cell: WorkItemCell?
}
if Sizing.cell == nil {
Sizing.cell = tableView.dequeueReusableCellWithIdentifier("WorkItemCell") as? WorkItemCell
}
if let cell = Sizing.cell {
cell.frame.size.width = CGRectGetWidth(tableView.bounds)
cell.workdic = workdic
let size = cell.catchcopyLabel.intrinsicContentSize()
return size.height
}
return 0
}