我想在UITableViewCell中设置我自己的cellAccessoryType(图像)。你知道我怎么做吗?我正在使用Swift,Xcode 6.2和iOS 8.2。谢谢你的帮助!
答案 0 :(得分:12)
试试这个:
// first create UIImageView
var imageView : UIImageView
imageView = UIImageView(frame:CGRectMake(20, 20, 100, 320))
imageView.image = UIImage(named:"image.jpg")
// then set it as cellAccessoryType
cell.accessoryView = imageView
PS:我强烈建议您升级到XCode 6.3.2并使用iOS 8.3 SDK
答案 1 :(得分:9)
我假设你想点击配件视图,所以我用按钮提供这个答案。 如果没有,请使用带有imageView的shargath答案。
var saveButton = UIButton.buttonWithType(.Custom) as UIButton
saveButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
saveButton.addTarget(self, action: "accessoryButtonTapped:", forControlEvents: .TouchUpInside)
saveButton.setImage(UIImage(named: "check-circle"), forState: .Normal)
cell.accessoryView = saveButton as UIView
func accessoryButtonTapped(sender:UIButton) {
}
答案 2 :(得分:1)
Swift 5版本,添加contentMode:
let imageView: UIImageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 20, height: 20)) imageView.image = UIImage(named:Imge.Card.Link.download) imageView.contentMode = .scaleAspectFit cell.accessoryView = imageView
答案 3 :(得分:0)
快速5版本的Shmidt的答案,以及使用sender.tag跟踪单击按钮的行:
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell",
for: indexPath)
let checkButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
checkButton.addTarget(self, action:#selector(YOUR_CLASS_NAME.checkTapped(_:)),
for: .touchUpInside)
checkButton.setImage(UIImage(named: "check"), for: .normal)
checkButton.tag = indexPath.row
cell.accessoryView = checkButton
return cell
}
@objc func checkTapped(_ sender: UIButton) {
print(sender.tag)
}
答案 4 :(得分:0)
Xamarin.iOS版本的Shmidt的答案
// Create the accessory
var accessory = new UIButton(UIButtonType.Custom);
accessory.Frame = new CGRect(0f, 0f, 24f, 24f);
accessory.AddTarget(accessoryButtonTapped, UIControlEvent.TouchUpInside);
accessory.SetImage(UIImage.FromBundle("check-circle"), UIControlState.Normal);
// Set the accessory to the cell
cell.AccessoryView = accessory as UIView;
void accessoryButtonTapped(object sender, EventArgs args)
{
}
答案 5 :(得分:0)
SWIFT 5 解决方案
此示例展示了如何将带有 SF 符号的简单按钮添加到您的附件视图中。
在 cellForRowAt 内:
let plusButton = UIButton(type: .system)
plusButton.setImage(UIImage(systemName: "plus"), for: .normal)
plusButton.contentMode = .scaleAspectFit
plusButton.sizeToFit()
cell.accessoryView = plusButton
我们可以使用 UITableViewDelegate 的委托方法代替向按钮添加目标
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
//handle logic here
}