[英]Button from UITableViewController sends data to detailViewController - swift
I have a problem that I cannot wrap my head around.. You cannot create a button action in a UITableViewController.. So I tried to just control + drag from the button to the detailtableViewController and pressed push.. But when I use prepareForSegue and I then click on the button it should send the button text to a string in the detailtableViewController, but sometimes it's not the correct name, because there are multiple cells in the tableView and the name is not always the same.. 我有一个问题,我不能包围我的头..你不能在UITableViewController中创建一个按钮动作..所以我试图控制+从按钮拖动到detailtableViewController并按下推..但当我使用prepareForSegue和我然后单击按钮,它应该将按钮文本发送到detailtableViewController中的字符串,但有时它不是正确的名称,因为tableView中有多个单元格,名称并不总是相同。
What I need it to do is, when you click the button "Button: 我需要它做的是,当你点击按钮“按钮:
It should go to this detailtableViewController: 它应该转到这个detailtableViewController:
With the name that is set as text to the Button. 将名称设置为Button的文本。 The variable that should receive the name of the button is called viaSegue and it is a string. 应该接收按钮名称的变量名为viaSegue,它是一个字符串。
My UITableViewController: 我的UITableViewController:
class feedTableViewController: UITableViewController, PostCellDelegate {
@IBOutlet weak var loadingSpinner: UIActivityIndicatorView!
@IBOutlet weak var profilePicture: UIImageView!
var sendName = "No name"
var facebookProfileUrl = ""
var dbRef: FIRDatabaseReference!
var updates = [Sweet]()
var gottenUserId : Bool? = false
var gottenUserIdWorkout : Bool? = false
override func viewDidLoad() {
super.viewDidLoad()
let logoImage = UIImageView(frame: CGRect(x:0, y:0, width: 60, height: 32))
logoImage.contentMode = .ScaleAspectFit
let logo = UIImage(named: "logo.png")
logoImage.image = logo
self.navigationItem.titleView = logoImage
loadingSpinner.startAnimating()
if let user = FIRAuth.auth()?.currentUser {
let userId = user.uid
let storage = FIRStorage.storage()
// Refer to your own Firebase storage
let storageRef = storage.referenceForURL("**********")
let profilePicRef = storageRef.child(userId+"/profile_pic.jpg")
// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
profilePicRef.dataWithMaxSize(1 * 300 * 300) { (data, error) -> Void in
if (error != nil) {
// Uh-oh, an error occurred!
print("Unable to download image")
} else {
// Data for "images/island.jpg" is returned
// ... let islandImage: UIImage! = UIImage(data: data!)
if (data != nil){
self.profilePicture.image = UIImage(data: data!)
self.profilePicture.layer.cornerRadius = self.profilePicture.frame.size.width/2
self.profilePicture.clipsToBounds = true
}
}
}
}
dbRef = FIRDatabase.database().reference().child("feed-items")
startObersvingDB()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 205
}
func startObersvingDB() {
FIRDatabase.database().reference().child("feed-items").queryOrderedByChild("date").observeEventType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
var newUpdates = [Sweet]()
for update in snapshot.children {
let updateObject = Sweet(snapshot: update as! FIRDataSnapshot)
newUpdates.append(updateObject)
}
self.updates = newUpdates.reverse()
self.tableView.reloadData()
}) { (error: NSError) in
print(error.description)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return updates.count
}
protocol PostCellDelegate: class {
func postCell(postCell: PostCell, didTouchUpInside button: UIButton)
}
func postCell(postCell: PostCell, didTouchUpInside button: UIButton) {
let identifier = "toDetailtableViewController"
let username = postCell.nameButton.titleLabel?.text
performSegue(withIdentifier: identifier, sender: username)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Lots of stuff happening here
My custom cell: 我的定制单元格:
class updateTableViewCell: UITableViewCell {
@IBOutlet weak var updateLabel: UILabel!
@IBOutlet weak var picView: UIImageView!
@IBOutlet weak var likesLabel: UILabel!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var hand: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var nameButton: UIButton!
weak var delegate: PostCellDelegate?
var pathDB : String!
var dbRef: FIRDatabaseReference!
var gottenUserId : Bool? = false
var sendNameCell = "No name here"
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func likeTapped(sender: AnyObject) {
//print(pathDB)
checkClickOnLikeButton()
}
@IBAction func didTouchUpInsideButton(sender: AnyObject) {
delegate?.postCell(self, didTouchUpInside: button)
}
func checkClickOnLikeButton() {
let dataPathen = self.pathDB
// print(dataPathen)
if let user = FIRAuth.auth()?.currentUser {
let userId = user.uid
FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
// Get user value
self.gottenUserId = snapshot.value![userId] as? Bool
// print(self.gottenUserId)
if self.gottenUserId == true {
print("Der er trykket high five før")
FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").child(userId).removeValue()
let greyButtonColor = UIColor(red: 85/255, green: 85/255, blue: 85/255, alpha: 1.0)
self.likeButton.setTitleColor(greyButtonColor, forState: UIControlState.Normal)
self.hand.image = UIImage(named: "high.png")
} else {
print("Der er IKKE trykket like før")
let quoteString = [userId: true]
FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").updateChildValues(quoteString)
let blueButtonColor = UIColor(red: 231/255, green: 45/255, blue: 60/255, alpha: 1.0)
self.likeButton.setTitleColor(blueButtonColor, forState: UIControlState.Normal)
self.hand.image = UIImage(named: "highfive.png")
}
// ...
}) { (error) in
print(error.localizedDescription)
}
}
}
}
Assuming you have already created a custom class for the cell containing the Button
, you must create an @IBAction
for the didTouchUpInside
event. 假设您已经为包含Button
的单元格创建了自定义类,则必须为didTouchUpInside
事件创建一个@IBAction
。 You must also create a segue directly from the UITableViewController
to the detailtableViewController
(so not from a button or a view, from one view controller to the other). 您还必须直接从UITableViewController
创建一个segue到detailtableViewController
(因此不能从按钮或视图,从一个视图控制器到另一个视图控制器)。 You will need to give this segue an identifier since we're going to be performing it manually. 您将需要为此segue提供一个标识符,因为我们将手动执行它。
Once you've hooked up the @IBAction
in the cell, we need a way of performing the segue from the cell. 一旦你在单元格中连接了@IBAction
,我们就需要一种从单元格中执行segue的方法。 To do this, we need a reference to the UITableViewController
. 为此,我们需要对UITableViewController
的引用。 We could get it using delegates or maybe responders, recently I've been using responders. 我们可以使用代表或响应者来获取它,最近我一直在使用响应者。
Delegate 代表
Create a protocol for your UITableViewController
to conform to. 为您的UITableViewController
创建一个符合的协议。
protocol PostCellDelegate: class {
func postCell(_ postCell: PostCell, didTouchUpInside button: UIButton)
}
Create a delegate variable in your custom cell class call it's didTouchUpInside
method from button's @IBAction
for that event. 在自定义单元类中创建一个委托变量,从该按钮的@IBAction
为该事件调用didTouchUpInside
方法。
weak var delegate: PostCellDelegate?
@IBAction func didTouchUpInsideButton() {
delegate?.postCell(self, didTouchUpInside: button)
}
Now in your UITableViewController
, you must conform to the delegate and set the delegate of the cells in the cellForRowAt
method. 现在在您的UITableViewController
,您必须符合委托并在cellForRowAt
方法中设置单元格的委托。
class tableViewController: UITableViewController, PostCellDelegate {
//...
// MARK: PostCellDelegate
func postCell(_ postCell: PostCell, didTouchUpInside button: UIButton) {
let identifier = "toDetailtableViewController"
let username = postCell.button.titleLabel?.text
performSegue(withIdentifier: identifier, sender: username)
}
//...
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.delegate = self
return cell
}
//...
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
switch (segue.destination, sender) {
case let (controller as detailtableViewController, username as String):
controller.usernameTextField.text = username
break
default:
break
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.