Swift UITableViewCell Alignment - uitableview

I am trying to display a page like the following
page title (left align)
region name(center align)
people in the region(subtitle with email in the detail label)
But if I choose subtitle as cell style, everything will be left aligned and I cannot change them in the code. Then If I choose custom as style the detailtextlabel will not show.
if(poDetailList.LastName == "POName"){
cell.backgroundColor = SharedClass().coopGroupHeaderColor
let selectedColor = UIView()
selectedColor.backgroundColor = SharedClass().coopGroupHeaderColor
cell.selectedBackgroundView = selectedColor
cell.textLabel?.textColor = UIColor.blackColor()
cell.textLabel?.font = UIFont.boldSystemFontOfSize(15.0)
cell.textLabel?.textAlignment = .Center
cell.accessoryType = .None
var t_header = ""
if(POShort != "OTHER" && POShort != "all" && POShort != "invalid"){
t_header = POName
}
else{
t_header = POName
}
cell.textLabel?.text = t_header
cell.detailTextLabel?.text = ""
cell.userInteractionEnabled = false;
} else{
cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.clearColor() : SharedClass().cellBackGroundColor
let selectedColor = UIView()
selectedColor.backgroundColor = SharedClass().selectedCellColor
cell.selectedBackgroundView = selectedColor
cell.textLabel?.font = UIFont.boldSystemFontOfSize(15.0)
cell.textLabel?.textAlignment = .Left
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
var t_header = poDetailList.FirstName
cell.textLabel?.text = "Name:" + poDetailList.FirstName + " " + poDetailList.LastName
cell.detailTextLabel?.text = "Not Responded In Days:" + poDetailList.DaysNotResponded
cell.userInteractionEnabled = true;
}
Can anyone help me with this?
Thank you very much

Set Alignment for both label
cell.textLabel?.textAlignment = .Left
cell.detailTextLabel?.textAlignment = .Right
i hope it work!!!

Related

why tableview cell is not displaying for the first time in iOS 15?

I have made my app completely Programatic UI. With iOS 15 I am having a weird issue however with previous iOS versions its working fine as expected. So I have couple of buttons on top of the view, while clicking each button the below table view will be reloaded. When I click on one particular button the table view cell is not showing anything but the space is occupied. At the same time if I press any other button and comeback to the same button everything looks perfect. Kindly check the below code and shed some light.
ModeOfPaymentTableViewCell
class ModeOfPaymentTableViewCell: UITableViewCell{
class var identifier: String { return String.className(self) }
let addressDescriptionTextView:UILabel = {
let textView = UILabel()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.textAlignment = .natural
textView.textColor = .gray
textView.font = K.FONT.FONT17
textView.isUserInteractionEnabled = false
textView.numberOfLines = 0
return textView
}()
let otherLabel:UILabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.textColor = UIColor.black
lbl.textAlignment = .natural
lbl.font = K.FONT.FONT17
return lbl
}()
let indicatorImage:UIImageView = {
let imageview = UIImageView()
imageview.translatesAutoresizingMaskIntoConstraints = false
imageview.image = #imageLiteral(resourceName: "Back")
return imageview
}()
let cardImage : UIImageView = {
let imageview = UIImageView()
imageview.translatesAutoresizingMaskIntoConstraints = false
imageview.contentMode = UIView.ContentMode.scaleAspectFit
return imageview
}()
var primaryData = [String](){
didSet{
setUpDescriptionTextView()
}
}
let shimmer = ShimmerCellWithOutImage()
var showShimmer = Bool(){
didSet{
shimmer.isHidden = !showShimmer
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
shimmer.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(shimmer)
self.addSubview(addressDescriptionTextView)
self.addSubview(otherLabel)
self.addSubview(cardImage)
self.addSubview(indicatorImage)
self.borderColor = UIColor.groupTableViewBackground
self.borderWidth = 1
self.backgroundColor = .white
self.selectionStyle = .none
setUpUI()
if Language.type == "en" || Language.type == "en-SA"{
otherLabel.textAlignment = .right
indicatorImage.image = #imageLiteral(resourceName: "Next")
}
else if Language.type == "ar" || Language.type == "ar-SA" {
otherLabel.textAlignment = .left
indicatorImage.image = #imageLiteral(resourceName: "Back")
}
else{
otherLabel.textAlignment = .right
indicatorImage.image = #imageLiteral(resourceName: "Next")
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("failed to load the frame")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override public func layoutSubviews() {
super.layoutSubviews()
shimmer.shimmerView.addShimmerAnimation()
}
func setUpDescriptionTextView(){
let leftSideValue = primaryData[0].components(separatedBy: ",")
let attributedText = NSMutableAttributedString()
attributedText.append(NSAttributedString(
string: "\n" + leftSideValue[0], attributes:
[NSAttributedString.Key.foregroundColor :
UIColor(hex:K.COLOR.GRAYTEXTCOLOR),NSAttributedString.Key.font:K.FONT.BOLDFONT12!]))
attributedText.append(NSAttributedString(
string: "\n" + "\(leftSideValue[1])" + "\n", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black,NSAttributedString.Key.font:K.FONT.FONT17!]))
addressDescriptionTextView.attributedText = attributedText
if primaryData[1] != " 0.0 " && primaryData[1] != ""{
// otherLabel.set(image: UIImage.directionIndicator()!, with: primaryData[1])
let data = primaryData[1];
if data == "VISA" || data == "MADA" || data == "MASTER"{
if data == "VISA" {
cardImage.image = #imageLiteral(resourceName: "visa")
}else if data == "MADA"{
cardImage.image = #imageLiteral(resourceName: "mada")
}else if data == "MASTER"{
cardImage.image = #imageLiteral(resourceName: "mascard")
}else{
cardImage.image = #imageLiteral(resourceName: "CARDS")
}
otherLabel.isHidden = true
cardImage.isHidden = false
}else{
otherLabel.text = data
otherLabel.isHidden = false
cardImage.isHidden = true
}
otherLabel.tintColor = UIColor(hex:K.COLOR.BLUE)
}else{
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setUpUI() {
[shimmer.topAnchor.constraint(equalTo: topAnchor,constant: 2),
shimmer.leadingAnchor.constraint(equalTo:leadingAnchor, constant: 0),
shimmer.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0),
shimmer.bottomAnchor.constraint(equalTo: bottomAnchor,constant:-2)].forEach{$0.isActive = true}
[addressDescriptionTextView.topAnchor.constraint(equalTo: topAnchor,constant: 0),
addressDescriptionTextView.leadingAnchor.constraint(equalTo:leadingAnchor, constant: 10),
addressDescriptionTextView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -UIScreen.main.bounds.width/2),
addressDescriptionTextView.bottomAnchor.constraint(equalTo: bottomAnchor,constant:0)].forEach{$0.isActive = true}
[otherLabel.topAnchor.constraint(equalTo: topAnchor,constant: 0),
otherLabel.leadingAnchor.constraint(equalTo: addressDescriptionTextView.trailingAnchor, constant: 2),
otherLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -25),
otherLabel.bottomAnchor.constraint(equalTo: bottomAnchor,constant:0)].forEach{$0.isActive = true}
[cardImage.topAnchor.constraint(equalTo: topAnchor,constant: 0),
// cardImage.leadingAnchor.constraint(equalTo: addressDescriptionTextView.trailingAnchor, constant: 2),
cardImage.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -25),
cardImage.bottomAnchor.constraint(equalTo: bottomAnchor,constant:0)].forEach{$0.isActive = true}
[indicatorImage.centerYAnchor.constraint(equalTo: centerYAnchor),
indicatorImage.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
indicatorImage.heightAnchor.constraint(equalToConstant: 15),
indicatorImage.widthAnchor.constraint(equalToConstant: 10)].forEach{$0.isActive = true}
}
}
EwalletDetailsViewController
Here the issue happens under case Reload:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.separatorStyle = .none
switch selectedType {
case "Activity":
let cell:generalActivityTableViewCell = tableView.dequeueReusableCell(
withIdentifier: generalActivityTableViewCell.identifier,
for: indexPath) as! generalActivityTableViewCell
let date = convertDateStringToFormatedDateString(date: self.activityData?.data?[indexPath.row].date_time ?? "")
cell.activityDescriptionDetails = "\(self.activityData?.data?[indexPath.row].title ?? "") & \(self.activityData?.data?[indexPath.row].desc ?? "")"
cell.activityValueDetails = "\(date) & \(self.activityData?.data?[indexPath.row].amount ?? "")"
return cell
case "Transfer":
if indexPath.row == 1{
if selectedEwalletForTransfer?.ewallet_number ?? "" == ""{
let cell:OtherAccountViewCell = tableView.dequeueReusableCell(
withIdentifier: OtherAccountViewCell.identifier,
for: indexPath) as! OtherAccountViewCell
return cell
}else{
let cell:ModeOfPaymentTableViewCell = tableView.dequeueReusableCell(
withIdentifier: ModeOfPaymentTableViewCell.identifier,
for: indexPath) as! ModeOfPaymentTableViewCell
cell.selectionStyle = .none
cell.showShimmer = false
cell.backgroundColor = UIColor.red
if selectedEwalletForTransfer?.ewallet_title == ""{
cell.primaryData = ["\("To Ewallet Account".localized())"+","+"\(selectedEwalletForTransfer?.ewallet_number ?? "")", "\(selectedEwalletForTransfer?.currency_label ?? "") "+"\(selectedEwalletForTransfer?.balance ?? "") " ]
}else{
cell.primaryData = ["\("To Ewallet Account".localized())"+","+"\(selectedEwalletForTransfer?.ewallet_number ?? "") "+"-"+" \(selectedEwalletForTransfer?.ewallet_title ?? "")" , "\(selectedEwalletForTransfer?.currency_label ?? "") "+"\(selectedEwalletForTransfer?.balance ?? "") " ]
}
return cell
}
}else{
let cell:ReloadPickerCell = tableView.dequeueReusableCell(
withIdentifier: ReloadPickerCell.identifier,
for: indexPath) as! ReloadPickerCell
cell.currencyPicker.delegate = self
cell.currencyPicker.dataSource = self
cell.amountPicker.delegate = self
cell.amountPicker.dataSource = self
cell.amountLabel.isHidden = false
cell.amountLabel.delegate = self
cell.selecteTitleLabel.text = "Enter Amount to transfer".localized()
return cell
}
case "Reload":
if indexPath.row == 1{
let cell:ModeOfPaymentTableViewCell = tableView.dequeueReusableCell(
withIdentifier: ModeOfPaymentTableViewCell.identifier,
for: indexPath) as! ModeOfPaymentTableViewCell
cell.selectionStyle = .none
cell.showShimmer = false
if self.selectedCard != nil{
cell.primaryData = ["\("CARD INFO".localized())"+","+"\(self.selectedCard?.card_masked_number ?? "")", "\(self.selectedCard?.card_brand ?? "")" ]
}else{
cell.primaryData = ["\("CARD INFO".localized())"+","+"Click here to add your credit card".localized(), "" ]
}
cell.layoutSubviews()
return cell
}else{
let cell:ReloadPickerCell = tableView.dequeueReusableCell(
withIdentifier: ReloadPickerCell.identifier,
for: indexPath) as! ReloadPickerCell
cell.currencyPicker.delegate = self
cell.currencyPicker.dataSource = self
cell.amountPicker.delegate = self
cell.amountPicker.dataSource = self
cell.amountLabel.isHidden = true
cell.selecteTitleLabel.text = "ENTER AMOUNT TO RELOAD".localized()
return cell
}
case "Share":
let cell:SharedTableViewCell = tableView.dequeueReusableCell(
withIdentifier: SharedTableViewCell.identifier,
for: indexPath) as! SharedTableViewCell
cell.showShimmer = false
let date = convertDateStringToFormatedDateString(date: self.shareData?.data?[indexPath.row].shared_date ?? "")
cell.primaryData = ["\(self.shareData?.data?[indexPath.row].shared_email ?? "")" + "," + "\(self.shareData?.data?[indexPath.row].user_name ?? "")","\(date)","\(self.shareData?.data?[indexPath.row].profile_pic ?? "")"]
return cell
default:
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
switch selectedType {
case "Activity":
return UITableView.automaticDimension
case "Transfer":
if indexPath.row == 1{
if selectedEwalletForTransfer?.ewallet_number ?? "" == ""{
return 120
}else{
return UITableView.automaticDimension
}
}else{
return 110
}
case "Reload":
if indexPath.row == 1{
if self.cardData?.data?.count == 0{
return UITableView.automaticDimension
}else{
return UITableView.automaticDimension
}
}else{
return 110
}
case "Share":
return UITableView.automaticDimension
default:
return 0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch selectedType {
case "Activity":
return UITableView.automaticDimension
case "Transfer":
if indexPath.row == 1{
if selectedEwalletForTransfer?.ewallet_number ?? "" == ""{
return 120
}else{
return UITableView.automaticDimension
}
}else{
return 110
}
case "Reload":
if indexPath.row == 1{
if self.cardData?.data?.count == 0 || self.cardData?.data == nil && OPPPaymentProvider.deviceSupportsApplePay() && self.selectedEwallet?.currency_code == "SAR" {
return UITableView.automaticDimension
}else{
return UITableView.automaticDimension
}
}else{
return 110
}
case "Share":
return UITableView.automaticDimension
default:
return 0
}
}

How to change the background color of the UItableview cell accesoryType?

I am using an UITableviewCell's Accessory type checkmark property to distinguish the selected cell with the other cells, but I tend to get this weird background view below it ?
cell!.selectionStyle = .none
cell?.backgroundColor = UIColor.clear
cell?.tintColor = UIColor(hexString: "#866bff")
cell?.contentView.backgroundColor = UIColor(hexString: "#F8F9FA")
cell!.textLabel!.font = UIFont(name: "OpenSans", size: optionsSize)
cell!.textLabel!.textColor = UIColor(hexString: "#484D57") //optionsTextColor ?? tint ?? cell!.textLabel!.textColor
cell!.textLabel!.textAlignment = optionsTextAlignment ?? cell!.textLabel!.textAlignment
cell!.textLabel!.text = "\(options[indexPath.row])"
//cell!.accessoryType = indexPath.row == selectedIndex ? .checkmark : .none
if(indexPath.row == selectedIndex){
cell?.accessoryType = .checkmark
}else{
cell?.accessoryType = .none
}
cell?.textLabel?.textColor = indexPath.row == selectedIndex ? UIColor(hexString: "#866bff") : tint
return cell!
As the comment, change the cell's backgroundColor to match cell's contentView backgroundColor fixed it since accessoryView is not related to cell's contentView and it will use cell background color as it's background color

How to add data for particular index in uitableview swift 3

I am creating a dynamic uilabel in CellforRowat for particuklar index i.e indexpath.row=0
But When I Scroll down I am seeing that UI Label on 4th Index as well ....
Why is it coming on 3rd index if I have already added a condition in Cellforroat as:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// var cell:ActivityMainTableViewCell?
if(CheckFlag == false){
//CheckFlag = true
}
else{
CheckFlag = false
}
// cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! as? ActivityMainTableViewCell
let cell:ActivityMainTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! ActivityMainTableViewCell
/// let cell = tableView.cellForRow(at: indexPath) as! ActivityMainTableViewCell
///let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ActivityMainTableViewCell
/// cell.viewheight.constant = 0
cell.imgViewFirst.layer.cornerRadius = (cell.imgViewFirst.frame.size.width) / 2
cell.imgViewFirst.layer.borderWidth = 3.0
cell.imgViewFirst.layer.borderColor = UIColor.white.cgColor
cell.imgViewFirst.clipsToBounds = true
cell.ImageViewThird.layer.cornerRadius = (cell.ImageViewThird.frame.size.width) / 2
cell.ImageViewThird.layer.borderWidth = 3.0
cell.ImageViewThird.layer.borderColor = UIColor.white.cgColor
cell.ImageViewThird.clipsToBounds = true
cell.ImageViewSecond.layer.cornerRadius = (cell.ImageViewSecond.frame.size.width) / 2
cell.ImageViewSecond.layer.borderWidth = 3.0
cell.ImageViewSecond.layer.borderColor = UIColor.white.cgColor
cell.ImageViewSecond.clipsToBounds = true
print(indexPath)
print(indexPath.row)
print(dicArray)
cell.DateOfMeeting.text = dicArray[indexPath.row]["Date"] as? String
cell.CompanyInMeetiong.text = dicArray[indexPath.row]["Company"] as? String
cell.lblNews.text = dicArray[indexPath.row]["News"] as? String
cell.lblCommonKey.text = dicArray[indexPath.row]["CommonKey"] as? String
print(SectordicArray)
cell.imgViewFirst.isHidden = true
cell.lblCommonKey.isHidden = true
cell.btnOthers.tag = indexPath.row
//for i in 0..<section.count {
print(cell.lblCommonKey.text)
print(indexPath.row)
RowHeight = 110.0
CellHeight = 140.0
isFirstTime = true
// print(AllCompanydicArray)
if(indexPath.row == 0){
let Data = AllCompanydicArray[indexPath.row]
print(Data)
for i in 0..<Data.count {
print(Data[i])
if(isFirstTime == false){
RowHeight = RowHeight + 30.0
CellHeight = CellHeight + 30.0
}
else{
isFirstTime = false
}
let Company = (Data[i] as NSDictionary).value(forKey: "Company") as! [String]
let Contacts = (Data[i] as NSDictionary).value(forKey: "Participants") as! [String]
// section.append(Company)
//items.append(Contacts)
for k in 0..<Company.count {
let newLabel = UILabel(frame: CGRect(x: 10.0, y: RowHeight, width:cell.frame.width, height: 30.0))
newLabel.text = Company[k]
newLabel.font = UIFont(name:"HelveticaNeue-Bold", size: 13)
cell.addSubview(newLabel)
}
for j in 0..<Contacts.count {
RowHeight = RowHeight + 30.0
CellHeight = CellHeight + 30.0
var
newLabel = UILabel(frame: CGRect(x: 10.0, y: RowHeight, width:30, height: 30.0))
newLabel.text = CaptionName(Name: Contacts[j])
//"RC"
newLabel.font = UIFont(name:"HelveticaNeue-Bold", size: 11)
newLabel.textAlignment = .center
newLabel.backgroundColor = getColorByHex(rgbHexValue: 0x002366, alpha: 0.9)// UIColor(red: 0.0, green: 14.0, blue: 40.0, alpha: 100.0)
newLabel.layer.cornerRadius = (newLabel.frame.size.width) / 2
newLabel.layer.borderWidth = 1.0
newLabel.clipsToBounds = true
newLabel.textColor = UIColor.white
newLabel.layer.borderColor = UIColor.white.cgColor
cell.addSubview(newLabel)
newLabel = UILabel(frame: CGRect(x: 50, y: RowHeight, width:cell.frame.width-30, height: 30.0))
newLabel.text = Contacts[j]//"Raghav Chopra"
newLabel.font = UIFont(name:"HelveticaNeue", size: 12)
cell.addSubview(newLabel)
}
}
}
else{
}
return cell
}
Please let me know how can i avoid uilabel on 4th index.

iOS Swift TableviewCell issue

I have a strange problem with tableView cell.
when I scroll tableView and cell disappear and back again to the cell I understand that tableView add similar cell exactly on cell.
for example look at the picture . 3 exact text add on each other.
cellForRowAtIndexPath function :
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
if indexPath.row == 0 {
let reviewNumber = UILabel()
if (self.book.review_count == 0) {
reviewNumber.text = "\(self.lang.book["no_review"]!)"
}
if (self.book.review_count > 0) {
reviewNumber.text = "\(self.book.review_count!) \(self.lang.general["review"]!)"
}
reviewNumber.textAlignment = .Right
reviewNumber.font = UIFont(name: "Vazir", size: 14)
reviewNumber.numberOfLines = 0
reviewNumber.translatesAutoresizingMaskIntoConstraints = false
reviewNumber.textColor = UIColor.grayColor()
cell.contentView.addSubview(reviewNumber)
let voteIcon = UIImageView()
voteIcon.image = UIImage(named: "vote-icn")
voteIcon.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(voteIcon)
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[v0(24)]-|",options: [],metrics: nil,views: ["v0" : voteIcon]))
let reviewIcon = UIImageView()
reviewIcon.image = UIImage(named: "review-icn")
reviewIcon.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(reviewIcon)
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[v0(24)]-|",options: [],metrics: nil,views: ["v0" : reviewIcon]))
let voteNumber = UILabel()
voteNumber.text = " ۴.۵ از ۱۶۵۴رأی"
voteNumber.textAlignment = .Left
voteNumber.font = UIFont(name: "Vazir", size: 14)
voteNumber.numberOfLines = 0
voteNumber.translatesAutoresizingMaskIntoConstraints = false
voteNumber.textColor = UIColor.grayColor()
cell.contentView.addSubview(voteNumber)
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-3-[v0]-3-|",options: [],metrics: nil,views: ["v0" : reviewNumber]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-3-[v0]-3-|",options: [],metrics: nil,views: ["v0" : voteNumber]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-35-[v0]-8-[v1(25)]",options: [],metrics: nil,views: ["v0" : voteNumber, "v1" : voteIcon, "v2" : reviewNumber, "v3" : reviewIcon]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v2]-8-[v3(25)]-35-|",options: [],metrics: nil,views: ["v0" : voteNumber, "v1" : voteIcon, "v2" : reviewNumber, "v3" : reviewIcon]))
}
if indexPath.row == 1 {
let userBookStatusButtn = UIButton(type: .Custom)
userBookStatusButtn.setTitle("خواهم خواند", forState: .Normal)
userBookStatusButtn.alpha = 0.2
userBookStatusButtn.titleLabel?.font = UIFont(name: "Vazir", size: 14)
userBookStatusButtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
// userBookStatusButtn.setImage(UIImage(named: "vote-icn"), forState: .Normal)
userBookStatusButtn.translatesAutoresizingMaskIntoConstraints = false
userBookStatusButtn.backgroundColor = UIColor(red:0.0/256.0 ,green:150.0/256.0, blue:136.0/256.0 ,alpha:1 )
cell.contentView.addSubview(userBookStatusButtn)
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[v0(48)]-20-|",options: [],metrics: nil,views: ["v0" : userBookStatusButtn]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-35-[v0]-35-|",options: [],metrics: nil,views: ["v0" : userBookStatusButtn]))
}
if indexPath.row == 2 {
let topBorder = UIView()
topBorder.translatesAutoresizingMaskIntoConstraints = false
topBorder.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
cell.contentView.addSubview(topBorder)
let bottomBorder = UIView()
bottomBorder.translatesAutoresizingMaskIntoConstraints = false
bottomBorder.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
cell.contentView.addSubview(bottomBorder)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
paragraphStyle.baseWritingDirection = .RightToLeft
guard let descriptionStr = self.book.description else {return cell}
let attrString = NSMutableAttributedString(string: descriptionStr)
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
let description = UILabel()
description.attributedText = attrString
description.textAlignment = .Justified
description.font = UIFont(name: "Vazir", size: 14)
description.numberOfLines = 0
description.translatesAutoresizingMaskIntoConstraints = false
description.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.contentView.addSubview(description)
let title = UILabel()
title.text = "\(self.lang.book["summery"]!)"
title.alpha = 0.2
title.textAlignment = .Center
title.font = UIFont(name: "Vazir-Bold", size: 16)
title.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(title)
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[v0]-|",options: [.AlignAllCenterX],metrics: nil,views: ["v0" : title]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[v0]-20-|",options: [],metrics: nil,views: ["v0" : description]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-8-[v1]-44-[v0]",options: [],metrics: nil,views: ["v0" : description,"v1" : title ]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0]-8-|",options: [],metrics: nil,views: ["v0" : description,"v1" : title ]))
}
cell.textLabel?.text = nil
return cell
}
I get data from son file with Alamofire and reloadData :
func tableRefresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.bookDetailTableView.reloadData()
})
}
what's my problem?
thanks guys.
You made a classical error when using iOS cells.
(I am a teacher, so I see this kind of error frequently... don't worry..)
some Considerations:
1) NEVER add a label to a cell. Doing so, very time a cell is reused, previous label stays here, and a new label is added
2) as label are transparent, you will see all text overlapped..
3) You are leaking memory, as no one will detach/ release labels.
so the way can be:
A)Simple for simple case
use TAGS, as Apple did on old days of cells..
(code i
make some defines:
let TEXT_TAG = 2000
add label if not present, if present get it vi TAG:
let cell = tableView.dequeueReusableCell(withIdentifier: REUSE, for: indexPath )
let text = "my text..."
if let label = cell.viewWithTag(TEXT_TAG) as? UILabel{
label.text = text
}else{
let frame = CGRect(x: 100, y: 20, width: 50, height: 50)
let label = UILabel(frame: frame)
label.text = text
cell.addSubview(label)
}
B) make a custom cell...
class CustomViewCell: UITableViewCell {
var label: UILabel?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let frame = CGRect(x: 100, y: 20, width: 50, height: 50)
let label = UILabel(frame: frame)
self.addSubview(label)
}
in controller simply:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: REUSE,
for: indexPath ) as! CustomViewCell
cell.label = "my text"
I get your problem,you get the cell from tableView reuseable pool.The first problem,if you want change UITableViewCell View,you need to creat a son class of it.I get a function to fix it.
I use Stackoverflow first time,I don't know where can I put my code,so I write it under this sentence.
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
for let item in cell.contentView.subviews {
item.removeFromSuperView();
}
And then using your code,it should help you.

Add UILabels programmatically to a Collection Cell, swift

I am trying to add UILabels in the subView of my Collection Cell.
But when I scroll to the other cell and come back all the UIlabels appear on both cells and some are written under the other..
I tried with collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell , but when I used it none UIlabel was displayed ( I tried with breaking points, it doesn't go after the if statement)
How can I fix it??
Thanks!!!
class CollectionView: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var collection = [PFObject]()
#IBOutlet weak var collectionView: UICollectionView!
let sidePadding:CGFloat = 10
var checkLocation: Bool = false
override func viewDidLoad()
{
super.viewDidLoad();
self.collectionView!.delegate = self
self.collectionView!.dataSource = self
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.collection.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell
cell.layer.borderColor = UIColor.lightGrayColor().CGColor
cell.layer.borderWidth = 0.5
cell.layer.cornerRadius = 3
let collectionViewWidth = self.collectionView.bounds.size.width - self.sidePadding * 2
cell.frame.size.width = collectionViewWidth
let collectionViewHeight = self.collectionView.bounds.size.height/4.5
cell.frame.size.height = collectionViewHeight
// Display the country name
if let value = self.collection[indexPath.row]["Name"] as? String {
cell.cellTitle.text = String(Int(indexPath.row)) + "." + value
}
let width = (cell.bounds.width - 94 - 4*3 - 60 - 20)/4
let cellheight = CGFloat(6)
let cellheight1 = CGFloat(6 + 12 + 2)
var array = [String]()
if let MWl = collection[indexPath.row]["MW"] as? Int
{
if MWl == 1 {
array.append("M")
} else if MWl == 2 {
array.append("M")
array.append("W")
}
}
if let JAl = collection[indexPath.row]["JA"] as? Int
{
if JAl == 1 {
array.append("Jy")
} else if JAl == 2 {
array.append("Jy")
array.append("Ac")
}
}
if let HK = collection[indexPath.row]["HK"] as? Int
{
if HK == 1 {
array.append("HB")
} else if HK == 2 {
array.append("HB")
array.append("Ks")
}
}
if let SSl = collection[indexPath.row]["SSl"] as? Int
{
if SSl == 1 {
array.append("AB")
} else if SSl == 2 {
array.append("AB")
array.append("CD")
}
//I tried here too
// if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell
if array.count <= 4 {
for i in 0..<array.count {
let taille = CGFloat(i)
var si = CGFloat((1+i)*3 + 94 + 30)
let label = UILabel() as UILabel
label.frame = CGRectMake((si + width*taille), cellheight, width, 12)
label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
label.backgroundColor = UIColor.clearColor()
label.layer.borderWidth = 0.7
label.layer.borderColor = UIColor.lightGrayColor().CGColor
label.font = UIFont(name: "Futura-Medium", size: 9)
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 1
label.text = array[i]
label.layer.masksToBounds = true
label.layer.cornerRadius = 3.5
if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
myCell.contentView.addSubview(label)
}
}
} else {
for i in 0...3 {
let taille = CGFloat(i)
var si = CGFloat((1+i)*3 + 94 + 30)
let label = UILabel() as UILabel
label.frame = CGRectMake((si + width*taille), cellheight, width, 12)
label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
label.backgroundColor = UIColor.clearColor()
label.layer.borderWidth = 0.7
label.layer.borderColor = UIColor.lightGrayColor().CGColor
label.font = UIFont(name: "Futura-Medium", size: 9)
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 1
label.text = array[i]
label.layer.masksToBounds = true
label.layer.cornerRadius = 3.5
if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
myCell.contentView.addSubview(label)
}
}
var j = 0 as Int
for i in 4..<array.count {
let taille = CGFloat(j)
let si = CGFloat((1+j)*3 + 94 + 30)
let label = UILabel() as UILabel
label.frame = CGRectMake((si + width*taille), cellheight1, width, 12)
label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
label.backgroundColor = UIColor.clearColor()
label.layer.borderWidth = 0.7
label.layer.borderColor = UIColor.lightGrayColor().CGColor
label.font = UIFont(name: "Futura-Medium", size: 9)
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 1
label.text = array[i]
label.layer.masksToBounds = true
label.layer.cornerRadius = 3.5
if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
myCell.contentView.addSubview(label)
}
j = j + 1
}
}
return cell
}
}
EDIT
I tried to create the UILabel programmatically. But in that way I used the elements designed with the StoryBoard and the elements created programmatically. And actually I can't because of this :
collectionView!.registerClass(RDCell.self, forCellWithReuseIdentifier: "Cell")
I create all the content of the cell programmatically ( the collectionView is created with the storyboard) and it works perfectly.
The cell is being reused, therefore you are always adding new labels each time cellForItemAtIndexPath is called. Just tag your labels like label.tag = 1 and when you dequeue the cell remove every subview with this tag, like
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell
for view in cell.subviews {
if view.tag == 1 {
view.removeFromSuperview()
}
}
You will be always recreating the labels though, which is bad design. I suggest designing those labels on storyboard or if you insist on doing it in code keep optional references to the label in the cell to not recreate them each time cellForItemAtIndexPath is called.
not recommended but you can do is,
Add tag to each label like 1000 or something and find sub views of cell if any of subview tag matches with label tag remove that view
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell
for let labelIs in cell.subviews
{
if labelIs.tag == 1000
{
labelIs.removeFromSuperview()
}
}
//some whare
var label = UILabel()
label.tag = 1000
return cell
}

Resources