How do I change the image of button on click? - ios

I have a preset image of a button in a custom cell, and I want that image to change when the button is clicked. How would I do that? I put a switch in the button, and it works. When it is clicked it will play a song, and when it is clicked again it will stop. I just want the image to change. How would I do that? The name of the button is playbutton.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = friendstable.dequeueReusableCellWithIdentifier("friendcell", forIndexPath: indexPath) as! FriendsMusicCell
cell.playbutton.tag = indexPath.row
cell.playbutton.addTarget(self, action: "playmusic:", forControlEvents: .TouchUpInside)
cell.customtitle.text = titleofsong[indexPath.row]
cell.customartist.text = artist[indexPath.row]
cell.customtitle.font = UIFont(name: "Lombok", size: 22)
cell.customtitle.textColor = UIColorFromRGB("4A90E2")
cell.customartist.font = UIFont(name: "Lombok", size: 16)
cell.customartist.textColor = UIColor.blackColor()
cell.customtitle.numberOfLines = 0;
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.backgroundColor = UIColor.clearColor()
return cell
}
func playmusic(sender: UIButton!) {
let playButtonrow = sender.tag
print(titleofsong[playButtonrow])
switch(buttonState){
case 0:
let searchTerm: String = titleofsong[playButtonrow]
let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music"
let url: NSURL = NSURL(string: urlPath)!
print("Search iTunes API at URL \(url)")
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) -> Void in
do {
if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
{
let previewUrl = NSURL(string: (dict["results"]![0]["previewUrl"] as? String)!)!
print(previewUrl)
self.player = AVPlayer(URL: previewUrl)
self.player.rate = 1.0
self.player.play()
}
} catch let jsonError as NSError {
}
}
task.resume()
}
buttonState = 1;
break;
case 1:
player.pause()
buttonState = 0;
default: break
}
}

You don't need to declare playButton globally
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = friendstable.dequeueReusableCellWithIdentifier("friendcell", forIndexPath: indexPath) as! FriendsMusicCell
cell.playbutton.tag = indexPath.row
cell.playButton.setImage(playImage, forState: UIControlState.Normal)
cell.playButton.setImage(pauseImage, forState: UIControlState.Selected)
cell.playbutton.addTarget(self, action: "playmusic:", forControlEvents: .TouchUpInside)
cell.customtitle.text = titleofsong[indexPath.row]
cell.customartist.text = artist[indexPath.row]
cell.customtitle.font = UIFont(name: "Lombok", size: 22)
cell.customtitle.textColor = UIColorFromRGB("4A90E2")
cell.customartist.font = UIFont(name: "Lombok", size: 16)
cell.customartist.textColor = UIColor.blackColor()
cell.customtitle.numberOfLines = 0;
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.backgroundColor = UIColor.clearColor()
return cell
}
in your playmusic function you can add the following line at the beginning
sender.selected = !sender.selected

It 's so easy. You can set image for uibutton with UIControlState
ex:
self.btnPlay.setImage(playImage, forState: UIControlState.Normal)
self.btnPlay.setImage(pauseImage, forState: UIControlState.Selected)
And When you click it, you change state of btnPlay:
self.btnPlay.selected = !self.btnPlay.selected

Related

UITableView when click button and change its image Swift 4

I have a problem when I click a button in UITableView.
When I click a button to change its image, another indexpath changes it image.
Two buttons change their image when I click one button.
This video is shown the problem :
Video Shown Problem
This is my code to button click :
#objc func btnAction(_ sender: UIButton) {
let section = 0
let row = sender.tag
let indexPath = IndexPath(row: row, section: section)
//let point = sender.convert(CGPoint.zero, to: servicestable as UIView)
// let indexPath: IndexPath! = servicestable.indexPathForRow(at: point)
let cell: ServicesCell = self.servicestable.cellForRow(at: indexPath) as! ServicesCell
print(sender.tag)
if services[indexPath.row].choose == "0" {
cell.check.setImage(UIImage(named: "Rectangle1"), for: .normal)
services[indexPath.row].choose = "1"
// checkchoose.updateValue(1, forKey: indexPath.row)
print("number: " + String(indexPath.row))
chooseservicesw.updateValue("0", forKey: String(indexPath.row+1))
// servicestable.reloadData()
}
else if services[indexPath.row].choose == "1" {
cell.check.setImage(UIImage(named: "checkbox1"), for: .normal)
services[indexPath.row].choose = "0"
// checkchoose.updateValue(0, forKey: indexPath.row)
print("number: " + String(indexPath.row))
chooseservicesw.removeValue(forKey: String(indexPath.row+1))
// servicestable.reloadData()
} }
and this is my code to Cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ServicesCell = servicestable.dequeueReusableCell(withIdentifier: "servicess", for: indexPath) as! ServicesCell
cell.name.text = services[indexPath.row].name
let photo = services[indexPath.row].icon
let imgURL = MainUrl + photo! // or jpg
// cell.icon.setImageFromURl(stringImageUrl: imgURL)
let url = URL(string: imgURL)
cell.icon.kf.setImage(with: url)
// print(checkchoose[indexPath.row])
print(services[indexPath.row].choose)
cell.check.tag = indexPath.row
cell.check.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)
cell.checkpay.tag = indexPath.row
cell.checkpay.addTarget(self, action: #selector(self.btnAction2(_:)), for: .touchUpInside)
cell.price.addTarget(self, action: #selector(self.endedit(_:)), for: .editingDidEnd)
cell.price.addTarget(self, action: #selector(self.endedit(_:)), for: .editingChanged)
cell.selectionStyle = .none
return cell
}
When you perform dequeueReusableCell, iOS not generates your array's counts of cells. Instead of this, it generates fewer cells and use these cells again and again on scrolls. In your case selected shown cells are actually same cells.
The solution: You should store the selection flag for your cells in your datasource array (in your case its services). And in cellForRowAt method you should select or deselect checkboxes according to your stored selection data.
Edit:
if services[indexPath.row].choose == "0" {
cell.check.setImage(UIImage(named: "Rectangle1"), for: .normal)
services[indexPath.row].choose = "1"
chooseservicesw.updateValue("0", forKey: String(indexPath.row+1))
} else if services[indexPath.row].choose == "1" {
cell.check.setImage(UIImage(named: "checkbox1"), for: .normal)
services[indexPath.row].choose = "0"
chooseservicesw.removeValue(forKey: String(indexPath.row+1))
}
Add this part to end of your cellForRowAt method.
This problem is because reuseable cell in Memory you can handle like that:
In Your ViewController or TableViewController add Array that handel selected Model selectedIndexPathServices Add your YourServiceModel
Example
class TableViewController: UITableViewController {
var selectedIndexPathServices :[YourServiceModel] = [YourServiceModel]()
override func viewDidLoad() {
super.viewDidLoad()
}
}
At your btnAction
#objc func btnAction(_ sender: UIButton) {
guard let cell = sender.superview?.superview as? ServicesCell else { return}
let indexPath = self.tableView.indexPath(for: cell)
if selectedIndexPathServices.contains(services[indexPath.row]){
selectedIndexPathServices.remove(at: indexPath.row)
}else{
selectedIndexPathServices.append(services[indexPath.row])
}
}
At your cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ServicesCell = servicestable.dequeueReusableCell(withIdentifier: "servicess", for: indexPath) as! ServicesCell
cell.name.text = services[indexPath.row].name
let photo = services[indexPath.row].icon
let imgURL = MainUrl + photo! // or jpg
// cell.icon.setImageFromURl(stringImageUrl: imgURL)
let url = URL(string: imgURL)
cell.icon.kf.setImage(with: url)
// print(checkchoose[indexPath.row])
if selectedIndexPathServices.contains(services[indexPath.row]){
if services[indexPath.row].choose == "0" {
cell.check.setImage(UIImage(named: "Rectangle1"), for: .normal)
services[indexPath.row].choose = "1"
chooseservicesw.updateValue("0", forKey: String(indexPath.row+1))
}
else if services[indexPath.row].choose == "1" {
cell.check.setImage(UIImage(named: "checkbox1"), for: .normal)
services[indexPath.row].choose = "0"
chooseservicesw.removeValue(forKey: String(indexPath.row+1))
}
}
cell.check.tag = indexPath.row
cell.check.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)
cell.checkpay.tag = indexPath.row
cell.checkpay.addTarget(self, action: #selector(self.btnAction2(_:)), for: .touchUpInside)
cell.price.addTarget(self, action: #selector(self.endedit(_:)), for: .editingDidEnd)
cell.price.addTarget(self, action: #selector(self.endedit(_:)), for: .editingChanged)
cell.selectionStyle = .none
return cell
}

addTarget to button action within nib of collection view

I have a keyboard extension in iOS 11 that includes a collection view of articles coming in from JSON. I have a button in the prototype cell that I would like to allow a user to press to open the article in Safari external to the keyboard. I can get it to open all links in a static URL, but I cant get it to open each article's URL. What am I missing?
I've put an example of the working simple static action and also included what I have tried but doesn't work in this code:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if(collectionView == self.key.colImages)
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gifCollectionViewCell", for: indexPath) as! gifCollectionViewCell
cell.lblTitle.text = self.articles[indexPath.row].headline
let prefix: String = "https://res.cloudinary.com/djvbbwrnm/image/fetch/"
let options: String = "w_0.2/"
if let imageURL = self.articles[indexPath.row].imageURL
{
let articleURL = self.articles[indexPath.row].url
let url = URL(string: articleURL!)
let urlAppended = prefix+options+imageURL
cell.imgView.sd_setImage(with: URL(string: urlAppended), completed: nil)
//This works
cell.shareButton.addTarget(self, action: #selector(openLink), for: .touchUpInside)
//This doesn't
cell.shareButton.addTarget(self, action: #selector(openUrl(url: url)), for: .touchUpInside)
}
return cell
}
else
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "catCollectionViewCell", for: indexPath) as! catCollectionViewCell
cell.imgView.image = buttPics[indexPath.row]
cell.imgView.layer.cornerRadius = 2
cell.imgView.layer.masksToBounds = true
return cell
}
}
#objc func openLink(){
let articleURL = "http://google.com"
let url = URL(string: articleURL)
openUrl(url: url)
}
#objc func openUrl(url: URL?) {
let selector = sel_registerName("openURL:")
var responder = self as UIResponder?
while let r = responder, !r.responds(to: selector) {
responder = r.next
}
_ = responder?.perform(selector, with: url)
}
You cant add any other DataTypes as arguments. Because, you are adding addTarget for UIButton.
#objc func openLink(){
}
#objc func openLink(sender: UIButton){ // URL is not possible.
}
The above two codes are same. In second one, you can access that UIButton's property.
Runnable Code
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if(collectionView == self.key.colImages)
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gifCollectionViewCell", for: indexPath) as! gifCollectionViewCell
cell.lblTitle.text = self.articles[indexPath.row].headline
let prefix: String = "https://res.cloudinary.com/djvbbwrnm/image/fetch/"
let options: String = "w_0.2/"
if let imageURL = self.articles[indexPath.row].imageURL
{
//let articleURL = self.articles[indexPath.row].url
//let url = URL(string: articleURL!)
let urlAppended = prefix+options+imageURL
cell.imgView.sd_setImage(with: URL(string: urlAppended), completed: nil)
//This works
cell.shareButton.addTarget(self, action: #selector(openLink), for: .touchUpInside)
//This doesn't
//cell.shareButton.addTarget(self, action: #selector(openUrl(url: url)), for: .touchUpInside)
cell.shareButton.tag = indexPath.row // SET TAG TO UIBUTTON
}
return cell
}
else
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "catCollectionViewCell", for: indexPath) as! catCollectionViewCell
cell.imgView.image = buttPics[indexPath.row]
cell.imgView.layer.cornerRadius = 2
cell.imgView.layer.masksToBounds = true
return cell
}
}
#objc func openLink(sender: UIButton){ // USE THIS.
let buttonTag : Int = sender.tag
let articleURL = self.articles[buttonTag].url
let url = URL(string: articleURL!)
// You can achieve by this way.
// Since I am in a keyboard extension, I added the follwoing code and it is working now.
let selector = sel_registerName("openURL:")
var responder = self as UIResponder?
while let r = responder, !r.responds(to: selector) {
responder = r.next
}
_ = responder?.perform(selector, with: url)
}

UITableView Checkmark not appearing when selected

I am using a UITableView on button click i am putting the tableview into edit mode I have added
tableView.allowMultiselectionduringedit = true
Here i am getting circles to select the table but no check mark is added when tapped. But code in didselectrow is getting executed
I have attached a picture
What should i change to get the rows selected
Code for didselect
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Did select Run")
if(isEditing){
let cell = chatTableView.cellForRow(at: indexPath)
cell?.setSelected(true, animated: true)
}else{
let groupMsg = groupMsgList[indexPath.row]
if(groupMsg.messageType == "file")
{
let fileNameString = groupMsg.fileOriginalName
if(fileNameString != nil){
let fileName: NSString = fileNameString! as NSString
let extention = fileName.pathExtension.lowercased()
switch extention {
case "jpg","png","jpeg":
if (groupMsg.senderUserId != LoginStatusInfo.userId){
let row = chatTableView.cellForRow(at: indexPath) as! PhotoReciveCell
chatTableView.beginUpdates()
row.downloadLabel.text = " Downloading... "
row.downloadLabel.sizeToFit()
row.downloadLabelConstraint.constant = 30.0
row.downloadLabel.layoutMargins = UIEdgeInsets(top: 2.0, left: 2.0, bottom: 2.0, right: 2.0)
downloadFileBackground(id: groupMsg.messageId!, fileName: groupMsg.message!, cellIndexPath: indexPath )
chatTableView.endUpdates()
}else{
let row = chatTableView.cellForRow(at: indexPath) as! PhotoSentCell
chatTableView.beginUpdates()
row.downloadLabel.text = " Downloading... "
row.downloadLabel.sizeToFit()
row.downloadLabelConstraint.constant = 30.0
row.downloadLabel.layoutMargins = UIEdgeInsets(top: 2.0, left: 2.0, bottom: 2.0, right: 2.0)
downloadFileBackground(id: groupMsg.messageId!, fileName: groupMsg.message!, cellIndexPath: indexPath )
chatTableView.endUpdates()
}
break
default :
if (groupMsg.senderUserId != LoginStatusInfo.userId){
let row = chatTableView.cellForRow(at: indexPath) as! FileRecieveCell
chatTableView.beginUpdates()
row.downloadStatusIndicator.isHidden = true
row.downloadingIndicator.alpha = 1.0
chatTableView.endUpdates()
}else{
let row = chatTableView.cellForRow(at: indexPath) as! FileSentCell
chatTableView.beginUpdates()
row.downloadStatusIndicator.isHidden = true
row.downloadingIndicator.alpha = 1.0
chatTableView.endUpdates()
}
downloadFileBackground(id: groupMsg.messageId!, fileName: groupMsg.fileOriginalName!, cellIndexPath: indexPath )
break
}
}
}
print(indexPath)
}
}
For CellatRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let groupMsg = groupMsgList[indexPath.row]
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(_:)))
groupId = groupMsg.groupId
//MARK: MessageType is textmessage
if (groupMsg.messageType == "message")
{
if (groupMsg.senderUserId != LoginStatusInfo.userId)
{
let cell : RecievedMessageCell = chatTableView.dequeueReusableCell(withIdentifier: "recieve") as! RecievedMessageCell
cell.name.text = groupMsg.senderDisplayName
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
// cell.message.sizeToFit()
cell.receiveMessageView.tag = indexPath.row
cell.receiveMessageView.addGestureRecognizer(longPressGesture)
return cell
}
else
{
let cell : SentMessageCell = chatTableView.dequeueReusableCell(withIdentifier: "send") as! SentMessageCell
// cell.sentMessageView.roundCorners(corners: [.topLeft,.topRight,.bottomLeft], radius: 20)
// cell.sentMessageView.layer.masksToBounds = false
cell.sentMessageView.layer.cornerRadius = 10
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
cell.messageStatus.isHidden = false
cell.messageStatus.text = groupMsg.status
// cell.message.sizeToFit()
cell.sentMessageView.tag = indexPath.row
cell.sentMessageView.addGestureRecognizer(longPressGesture)
return cell
}
}
//MARK: Message type is Banner
else if (groupMsg.messageType == "banner") {
let cell : BotBanner = chatTableView.dequeueReusableCell(withIdentifier: "botBanner") as! BotBanner
hasBanner = true
scrollToIndex = indexPath.row
return cell
}
//MARK: Message type is File
else{
if (groupMsg.senderUserId != LoginStatusInfo.userId)
{
//MARK: File Recived
let fileNameString = groupMsg.fileOriginalName
if(fileNameString != nil){
let fileName: NSString = fileNameString! as NSString
let extention = fileName.pathExtension.lowercased()
let cell : FileRecieveCell = chatTableView.dequeueReusableCell(withIdentifier: "fileRecieve") as! FileRecieveCell
let fileUrl = self.getImageURL(forFileName: fileNameString!)
if(fileUrl == nil){
cell.downloadStatusIndicator.image = #imageLiteral(resourceName: "fileDonwloadBlack")
}else{
cell.downloadStatusIndicator.image = #imageLiteral(resourceName: "downloadedBlack")
}
cell.downloadStatusIndicator.isHidden = false
cell.downloadingIndicator.alpha = 0.0
cell.receiveFileView.layer.cornerRadius = 10
cell.name.text = groupMsg.senderDisplayName
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
cell.fileIcon.image = returnImage(fileName:groupMsg.message!)
cell.receiveFileView.isUserInteractionEnabled = true
cell.receiveFileView.addGestureRecognizer(longPressGesture)
cell.receiveFileView.tag = indexPath.row
return cellname.text = groupMsg.senderDisplayName
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
cell.fileIcon.image = returnImage(fileName:groupMsg.message!)
cell.receiveFileView.isUserInteractionEnabled = true
cell.receiveFileView.addGestureRecognizer(longPressGesture)
cell.receiveFileView.tag = indexPath.row
return cell
}
}
else
{
let cell : FileSentCell = chatTableView.dequeueReusableCell(withIdentifier: "fileSend") as! FileSentCell
let fileUrl = self.getImageURL(forFileName: fileNameString!)
if(fileUrl == nil){
cell.downloadStatusIndicator.image = #imageLiteral(resourceName: "fileDownloadWhite")
}else{
cell.downloadStatusIndicator.image = #imageLiteral(resourceName: "downloadedWhite")
}
cell.downloadStatusIndicator.isHidden = false
cell.downloadingIndicator.alpha = 0.0
cell.sendFileView.layer.cornerRadius = 10
cell.name.text = groupMsg.senderDisplayName
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
cell.fileStatus.text = groupMsg.status
cell.fileIcon.image = returnImage(fileName:groupMsg.message!)
cell.sendFileView.tag = indexPath.row
cell.sendFileView.addGestureRecognizer(longPressGesture)
cell.sendFileView.isUserInteractionEnabled = true
return cell
}
}
}
}
Solved!
My Mistake was i needed to add cell.setSelectionStype = .default in cellForAtRow
Tableview use dequeueReusableCell , so you can
cell?.setSelected(true, animated: true)
When you scroll tableview , the same cell - reusable from a cell will is selected -> wrong.
In GroupMessage model add property: isSelected . and set
isSelected = true
self.tableview.reloadrowatindexpath ....
when didselected
In cellForRowAt indexPath
If groupMsg.isSelected{
cell?.setSelected(true, animated: true)
}else{
cell?.setSelected(false, animated: true)
}
OR create a NSMutableArray - selectedMessage to hold message selected didSelected add/remove groupmessage in selectedMessage
In cellForRowAt indexPath check selectedMessage contains groupmessage - setSelected = true or no

change button image when play completes swift

sender button changes when i click play button but when i click another button in the tableview the button first button image not changes to play
#IBAction func playSound(sender: UIButton) {
if self.player != nil && self.player.playing {
player.stop()
sender.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
}
else {
sender.setImage(UIImage(named: "pause.png"), forState: UIControlState.Normal)
}
}
**Try this code ...**
Declare one variable for get index.
var songnamearray : NSArray = NSArray()
var audioPlayer = AVAudioPlayer()
var selectedindex : Int?
var isFristtime : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
songnamearray = ["Saiyaan (Sanam) 320Kbps(MajMasti.in)" ,"Phone Mein Teri Photo (Neha Kakkar) - 320 Kbps(GoldMusic.In)" ,"Mile Ho Tum Humko (Neha Kakkar) - 320 Kbps(GoldMusic.In)" ," Rain Mashup (Neha Kakkar) - 320 Kbps(GoldMusic.In)" ,"Car Mein Music Baja (Neha Kakkar) 320Kbps"]
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songnamearray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Songcell", forIndexPath: indexPath)
// info 5 play 6 name 7
let eventname: UILabel = (cell.viewWithTag(7) as! UILabel)
let info: UIButton = (cell.viewWithTag(5) as! UIButton)
let play: UIButton = (cell.viewWithTag(6) as! UIButton)
if selectedindex == indexPath.row{
if isFristtime == true
{
play.setImage(UIImage(named: "pause-button.png"), forState: UIControlState.Normal)
}else{
play.setImage(UIImage(named: "play-button.png"), forState: UIControlState.Normal)
}
}else{
play.setImage(UIImage(named: "play-button.png"), forState: UIControlState.Normal)
}
info.setImage(UIImage(named: "icon (5).png"), forState: UIControlState.Normal)
play.addTarget(self, action: #selector(self.CloseMethod(_:event:)), forControlEvents: .TouchDown)
info.addTarget(self, action: #selector(self.CloseMethod1(_:event:)), forControlEvents: .TouchDown)
eventname.text = songnamearray.objectAtIndex(indexPath.row) as? String
return cell
}
#IBAction func CloseMethod(sender: UIButton, event: AnyObject) {
let touches = event.allTouches()!
let touch = touches.first!
let currentTouchPosition = touch.locationInView(self.Songlisttable)
let indexPath = self.Songlisttable.indexPathForRowAtPoint(currentTouchPosition)!
selectedindex = indexPath.row
if isFristtime == true
{
audioPlayer.pause()
isFristtime = false
}else{
let songnamestring : NSString = songnamearray.objectAtIndex(indexPath.row) as! String
do {
if let bundle = NSBundle.mainBundle().pathForResource(songnamestring as String, ofType: "mp3") {
let alertSound = NSURL(fileURLWithPath: bundle)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
} catch {
print(error)
}
isFristtime = true
}
self.Songlisttable.reloadData()
}
Try to set background image for button
let image = UIImage(named: "play.png") as UIImage
sender.setBackgroundImage(image, forState: UIControlState.Normal)
Hope this helps.
It is that call radio button. I never use radio button in cell. It is hard for me. I'm newbie. If U need it, it is that: Radio button logic in UItableViewCells.
But i use other way: didSelectRowAtIndexPath. When u click in cell, button current is show pause image, and other button is show play image. U can reference it
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
currentIndexPath = indexPath;
YourTableViewCell *cell = nil;
if (!previousIndexPath) {
previousIndexPath = currentIndexPath;
}
if (previousIndexPath != currentIndexPath) {
cell = (YourTableViewCell *) [_yourTableView cellForRowAtIndexPath:previousIndexPath];
[cell.radioBtn setBackgroundImage:[UIImage imageNamed:#"play"] forState:UIControlStateNormal];
cell = (YourTableViewCell *) [_yourTableView cellForRowAtIndexPath:currentIndexPath];
[cell.radioBtn setBackgroundImage:[UIImage imageNamed:#"pause"] forState:UIControlStateNormal];
previousIndexPath = currentIndexPath;
}
if (previousIndexPath == currentIndexPath) {
cell = (YourTableViewCell *) [_yourTableView cellForRowAtIndexPath:previousIndexPath];
[cell.radioBtn setBackgroundImage:[UIImage imageNamed:#"pause"] forState:UIControlStateNormal];
}
}

Table View Cell Content Repeating While I reload data

My table view cell is repeating when scroll while waiting to reload Data . After reload all item are reset and all repeating content are remove . Here a video showing the problem , anyone know why and how can i fixed it ? As you can see in the video the hdsdjhjdhhsdsjshhsdhsjhdjd is repeating again on the top?
https://www.dropbox.com/s/e0arcajkuuot8xa/Reflector%20Recording.mp4?dl=0
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:StatusTableCell! = tableView.dequeueReusableCellWithIdentifier("statusCell", forIndexPath: indexPath) as! StatusTableCell
if (cell == nil) {
cell.uploadDate = nil
cell.uploadStatus.text = nil
cell.statusUploader.setTitle("", forState: .Normal)
}
cell.photoImage.hidden = true
self.photoHidden = true
print("\n\n\n\n")
cell.layoutIfNeeded()
cell.likesButton.setImage(UIImage(named: "Likes"), forState: .Normal)
cell.likesButton.setTitle("0", forState: UIControlState.Normal)
print("\n\n\n\n")
//Makes The Cell Of Text View Detect Link
cell.uploadStatus.dataDetectorTypes = .Link
cell.uploadStatus.delegate = self
do {
print(date2)
cell.statusUploader.setTitle("\(user2[indexPath.row])", forState: UIControlState.Normal)
if isLoadingLikes == false {
//Modified Height Based ON Status NOTE: STILL BUGGY
cell.uploadStatus.text = status2[indexPath.row]
cell.uploadStatus.frame.size.height = textViewHeight(cell.uploadStatus)
test = cell.uploadStatus.frame.size.height
self.tableView(tableView, heightForRowAtIndexPath: indexPath)
//Likes Button Data
let uploadLikes = likes2[indexPath.row]
cell.likesButton.tag = indexPath.row
cell.likesButton.setTitle("\(uploadLikes)", forState: UIControlState.Normal)
//Add An Action Connector To Likes Button
cell.likesButton.addTarget(self, action: Selector("likesFunction:"), forControlEvents: .TouchUpInside)
cell.moreButton.addTarget(self, action: Selector("moreFunction:"), forControlEvents: .TouchUpInside)
print(liked2)
if liked2[indexPath.row] == "liked" {
cell.likesButton.setImage(UIImage(named: "Likes2"), forState: .Normal)
}else {
cell.likesButton.setImage(UIImage(named: "Likes"), forState: .Normal)
}
}
print("----------------------------- Row \(indexPath.row)")
print("Checking Date Array\(date2[indexPath.row])")
print("Check NSDATE \(NSDate().timeIntervalSinceDate(date2[indexPath.row]))")
print("Checking TIME FORMATTER \(timeAgoSinceDate(date2[indexPath.row], numericDates: true))")
print("Status = \(status2[indexPath.row])")
cell.uploadDate.text = timeAgoSinceDate(date2[indexPath.row], numericDates: true)
let stringWithNSDataDetector: String = cell.uploadStatus.text
let error: NSError? = nil
let dataDetector: NSDataDetector = try NSDataDetector(types: NSTextCheckingType.Link.rawValue)
//Check if (error) before
var allMatches: [AnyObject] = [AnyObject]()
dataDetector.enumerateMatchesInString(stringWithNSDataDetector, options: NSMatchingOptions.Anchored, range: NSMakeRange(0, stringWithNSDataDetector.characters.count), usingBlock: { (match:NSTextCheckingResult?, flags:NSMatchingFlags, pointer:UnsafeMutablePointer<ObjCBool>) -> Void in
print("Link \(match!.resultType == .Link)")
if match!.resultType == .Link {
allMatches.append(match!.URL!)
self.photoHidden = false
cell.photoImage.hidden = false
print(match!.URL!)
}
})
print("ALL Matches \(allMatches)")
print("Test \(test) -- row : \(indexPath.row)")
print(cell.uploadStatus.frame.size.height)
}
catch {
print("Error Loading Status -- (StatusTableView)")
}
print("----------------------------- End \n")
cell.setNeedsDisplay()
return cell
}
And here is another
func textViewHeight (textView:UITextView) -> CGFloat{
textView.scrollEnabled = false
let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame;
return textView.frame.height
}
internal func textViewHeightForText(text: String?, andWidth width: CGFloat) -> CGFloat {
let calculationView = UITextView()
//IMPORTANT - have to specify the name/size of your font
let attributedText = NSAttributedString(string: (text != nil) ? text! : "", attributes: [NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 16.0)!])
calculationView.attributedText = attributedText
let height = calculationView.sizeThatFits(CGSize(width: width, height: CGFloat.max)).height
return height
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let width = tableView.frame.size.width - 79
if photoHidden == false {
return textViewHeightForText(status2[indexPath.row], andWidth: width) + 260
}else {
return textViewHeightForText(status2[indexPath.row], andWidth: width) + 140
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("statusCell", forIndexPath: indexPath) as! StatusTableCell
cell.uploadStatus.text = status2[indexPath.row]
cell.uploadStatus.frame.size.height = textViewHeight(cell.uploadStatus)
test = cell.uploadStatus.frame.size.height
self.tableView(tableView, heightForRowAtIndexPath: indexPath)
//If it is last row of the loaded table views , it will loading it got more than one current object else finish loading
if (indexPath.row == objectCount - 1) && isLoadingMoreCell == false
{
self.isLoadingMoreCell = true
self.tableView.tableFooterView = footerView
footerLoading.center.x = self.footerView.frame.width/2
footerLoading.startAnimating()
loadMoreCell()
}
}

Resources