我有一个带有按钮的自定义表格视图单元,该按钮可以在该单元的右上角按下。按下时,该按钮应显示一个操作表。
但是,每当我尝试按下按钮时,单元格都会在didSelectRow中执行操作,而不是显示操作表。好像按钮不可按下,但应该可以按下。这是课程:
class BulletinPostTableViewCell: UITableViewCell {
//MARK : VARIABLES
var tapAction: ((UITableViewCell) -> Void)?
@IBOutlet weak var title: UILabel!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var userProfilePicture: UIImageView!
@IBOutlet weak var bulletinImage: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var optionsButton: UIButton!
@IBAction func optionsPressed(_ sender: Any) {
tapAction?(self)
}
func customInit(titleText: String, descriptionText: String, occupations: String){
self.title.text = titleText
self.descriptionTextView.text = descriptionText
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
以下是使用自定义单元格笔尖的视图控制器:
class HomeTableViewController: UITableViewController, UITextViewDelegate, UISearchBarDelegate {
//MARK : VARIABLES
var refHandle: UInt!
var ref: DatabaseReference!
var bulletin: Bulletin!
var bulletinArray = [Bulletin]()
var userObject: User!
let contactPickerViewController = CNContactPickerViewController()
let messageViewController = MFMessageComposeViewController()
@IBOutlet weak var searchBarOutlet: UIBarButtonItem!
//MARK : CUSTOM VARIABLES (FOR TRANSITION)
var uid: String = ""
var customTitle: String = ""
var customImage: String = ""
var customUserName: String = ""
var customOccupations: String = ""
var customTimeStamp: String = ""
var customDescription: String = ""
var customUserImage: String = ""
var customLink: String?
var floatingActionButton = ButtonWithImage(type: .custom)
var occupations: [String] = []
//MARK : ACTIONS
@IBAction func searchButtonPressed(_ sender: Any) {
//-- create a search button and then present it
let searchController = UISearchController(searchResultsController: nil)
//-- set any properties (in this case, don't hide the nav bar and don't show the emoji keyboard option)
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.keyboardType = UIKeyboardType.asciiCapable
//-- make this class the delegate and present the search
searchController.searchBar.delegate = self
present(searchController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = .none
fetchBulletins()
getCurrentUser()
//-- set table view heights
tableView.delegate = self
tableView.estimatedRowHeight = 60
tableView.rowHeight = UITableView.automaticDimension
//-- creates the nib for bulletin posts
let bulletinNib = UINib(nibName: "BulletinPostTableViewCell", bundle: nil)
tableView.register(bulletinNib, forCellReuseIdentifier: "newBulletinCell")
tableView.reloadData()
}
func getCurrentUser(){
let uid = Auth.auth().currentUser?.uid
let db = Firestore.firestore()
let docRef = db.collection("users").document(uid!)
docRef.getDocument { (document, err) in
if let dictionary = document?.data() {
let user = User(dictionary: dictionary as [String: AnyObject])
user.id = document?.documentID
self.userObject = user
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "selectedBulletinTransition" {
if let selectedView = segue.destination as? SelectedBulletinViewController {
selectedView.bulletin = bulletin
}
}
}
//MARK : CUSTOM ACTIONS
func fetchBulletins(){
let db = Firestore.firestore()
db.collection("bulletins").getDocuments { (snapshot, err) in
if let err = err {
print("Error:\(err)")
} else {
for document in snapshot!.documents {
var dictionary = document.data()
let bulletin = Bulletin(dictionary: dictionary as [String: AnyObject])
bulletin.id = document.documentID
self.bulletinArray.insert(bulletin, at: 0)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}
func showAlertForRow(bulletin: Bulletin) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.addAction((UIAlertAction(title: "Report", style: .default, handler: { (action) in
print("complete")
})))
alertController.addAction((UIAlertAction(title: "Block", style: .default, handler: { (action) in
print("complete")
})))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
// MARK : TABLE VIEW METHODS
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bulletinArray.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
bulletin = bulletinArray[indexPath.row]
self.performSegue(withIdentifier: "selectedBulletinTransition", sender: self)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let bulletin = self.bulletinArray[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "newBulletinCell", for: indexPath) as! BulletinPostTableViewCell
//-- set the properties for custom variables (title, description, occupations, image)
self.customTitle = bulletin.bulletinTitle!
self.customDescription = bulletin.bulletinDescription!
self.customLink = bulletin.bulletinLink
self.customUserName = bulletin.userName!
cell.userNameLabel.text = bulletin.userName!
if let userPicture = bulletin.userPhoto {
let url = URL(string: userPicture)
self.customUserImage = userPicture
cell.userProfilePicture.kf.setImage(with: url)
cell.userProfilePicture.layer.cornerRadius = 10
cell.userProfilePicture.layer.masksToBounds = true
cell.userProfilePicture.contentMode = .scaleAspectFill
}
//MARK: add action to cell button
cell.tapAction = { (cell) in
self.showAlertForRow(bulletin: bulletin)
}
//-- time
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yy, h:mm a"
let dateStamp = dateFormatter.date(from: bulletin.date)
cell.dateLabel.text = dateStamp!.timeAgoDisplay()
//-- if theres no description, don't show it.
if bulletin.bulletinDescription == nil || bulletin.bulletinDescription == ""{
cell.descriptionTextView.heightAnchor.constraint(equalToConstant: 0).isActive = true
}
//-- sets the properties for the cell image.
if bulletin.bulletinImage == nil {
cell.bulletinImage.heightAnchor.constraint(equalToConstant: 0).isActive = true
cell.bulletinImage.translatesAutoresizingMaskIntoConstraints = false
cell.customInit(titleText: bulletin.bulletinTitle!, descriptionText: String(bulletin.bulletinDescription!.prefix(180)) + "...", occupations: "")
if let occupationArray = bulletin.occupations as? [String]{
let occupationRepresentation = occupationArray.joined(separator: ", ")
}
} else {
if let thisCustomImage = bulletin.bulletinImage {
cell.customInit(titleText: bulletin.bulletinTitle!, descriptionText: String(bulletin.bulletinDescription!.prefix(90)) + "...", occupations: "")
if let occupationArray = bulletin.occupations as? [String]{
let occupationRepresentation = occupationArray.joined(separator: ", ")
}
self.customImage = thisCustomImage
let url = URL(string: thisCustomImage)
cell.bulletinImage.kf.setImage(with: url)
cell.bulletinImage.contentMode = .scaleAspectFill
cell.bulletinImage.layer.cornerRadius = 8.0
cell.bulletinImage.layer.masksToBounds = true
cell.bulletinImage.translatesAutoresizingMaskIntoConstraints = false
}
}
return cell
}
}
答案 0 :(得分:0)
检查故事板。 UIButton和Cell的ContentView之间的所有视图都需要将其UserInteractionEnabled设置为true。
答案 1 :(得分:0)
尝试禁用表格视图单元格选择功能。
tableView.allowsSelection = false