将UITableViewCell限制在UITableView的右边缘

问题描述 投票:0回答:1

由于某些原因,当我尝试使用以下方法在单元格上放置阴影时,它并没有达到单元格的整个宽度:

cell.layer.shadowPath = UIBezierPath(roundedRect:cell.bounds, cornerRadius:cell.contentView.layer.cornerRadius).cgPath

有人知道如何解决此问题吗?

当然,我的最终目的是在左右两侧都留出一定的间距,但我觉得第一步是使其达到边缘。

模拟器和情节提要:

simulator and the storyboard

代码:

//
//  SpendingCategoryViewController.swift
//  Spending
//
//  Created by user01 on 5/14/20.
//  Copyright © 2020 sritej. All rights reserved.
//

import UIKit

class SpendingCategoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    //MARK: Properties

    @IBOutlet weak var spendingCategoriesTableView: UITableView!
    var spendingCategories = [SpendingCategory]()

    override func viewDidLoad() {
        super.viewDidLoad()
        spendingCategoriesTableView.delegate = self
        spendingCategoriesTableView.dataSource = self

        // Load the sample data.
        loadSampleCategories()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return spendingCategories.count
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // Table view cells are reused and should be dequeued using a cell identifier.
        let cellIdentifier = "SpendingCategoryTableViewCell"

        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? SpendingCategoryTableViewCell  else {
            fatalError("The dequeued cell is not an instance of SpendingCategoryTableViewCell.")
        }

        // Fetches the appropriate SpendingCategory for the data source layout.
        let spendingCategory = spendingCategories[indexPath.row]

        cell.categoryLabel.text = spendingCategory.name
        cell.iconImageView.image = spendingCategory.icon
        cell.valueLabel.text = String(format: "$%.02f", spendingCategory.total)

        // This creates the shadows and modifies the cards a little bit
        // https://github.com/rileydnorris/cardLayoutSwift/blob/9b852fc8e1b7d62093be787a33a3a89d764dc9b8/cardLayout/ViewController.swift

        cell.contentView.layer.cornerRadius = 2.0
//        cell.contentView.layer.borderWidth = 1.0
        cell.contentView.layer.borderColor = UIColor.clear.cgColor
        cell.contentView.layer.masksToBounds = true;

        cell.layer.shadowColor = UIColor.lightGray.cgColor
        cell.layer.shadowOffset = CGSize(width:0,height: 2.0)
        cell.layer.shadowRadius = 2.0
        cell.layer.shadowOpacity = 1.0
        cell.layer.masksToBounds = false;
        cell.layer.shadowPath = UIBezierPath(roundedRect:cell.bounds, cornerRadius:cell.contentView.layer.cornerRadius).cgPath




        return cell
    }


    /*
     // Override to support conditional editing of the table view.
     override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
     // Return false if you do not want the specified item to be editable.
     return true
     }
     */

    /*
     // Override to support editing the table view.
     override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
     if editingStyle == .delete {
     // Delete the row from the data source
     tableView.deleteRows(at: [indexPath], with: .fade)
     } else if editingStyle == .insert {
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
     }
     }
     */

    /*
     // Override to support rearranging the table view.
     override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

     }
     */

    /*
     // Override to support conditional rearranging of the table view.
     override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
     // Return false if you do not want the item to be re-orderable.
     return true
     }
     */

    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

    //MARK: Private Methods
    @IBAction func addCategoryButtonPress(_ sender: UIButton) {
        // Create an alert
        let alert = UIAlertController(
            title: "Add a new category",
            message: "",
            preferredStyle: .alert)

        // Add a text field to the alert for the new item's title
        alert.addTextField(configurationHandler: nil)

        // Add a "cancel" button to the alert. This one doesn't need a handler
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        // Add a "OK" button to the alert. The handler calls addNewCategory()
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler:
            { (_) in
                // Get the title the user inserted, but only if it is not an empty string
                if let title = alert.textFields?[0].text, title.count > 0
                {
                    print("took in alert input")
                    self.addNewCategory(title: title)
                    //                    self.containerViewController?.viewDidLoad()
                }
        }))

        // Present the alert to the user
        self.present(alert, animated: true, completion: nil)
    }

    internal func addNewCategory(title: String)
    {
        // The index of the new item will be the current item count
        print("reached addNewCategory")
        let newIndex = spendingCategories.count

        // Create new item and add it to the todo items list
        spendingCategories.append(SpendingCategory(name: title, icon: UIImage(named: "Default")!, total: 0)!)

        // Tell the table view a new row has been created
        self.spendingCategoriesTableView.insertRows(at: [IndexPath(row: newIndex, section: 0)], with: .bottom)
        print(spendingCategories)
    }

    private func loadSampleCategories() {
        let photo1 = UIImage(named: "Default")

        guard let category1 = SpendingCategory(name: "Groceries", icon: photo1!, total: 4) else {
            fatalError("Unable to instantiate category1")
        }

        guard let category2 = SpendingCategory(name: "Transportation", icon: photo1!, total: 12345678) else {
            fatalError("Unable to instantiate category2")
        }

        guard let category3 = SpendingCategory(name: "Alcohol something really long", icon: photo1!, total: 12345) else {
            fatalError("Unable to instantiate category3")
        }

        spendingCategories += [category1, category2, category3]
    }
}

ios swift uitableview storyboard
1个回答
0
投票

永远不要在单元格上添加阴影。为此,请在UIView的子视图中添加UITableViewCell,并为其提供顶部,底部,前导尾迹边距,并向该视图添加阴影/角半径。现在,将所有ui组件添加到子视图中。

© www.soinside.com 2019 - 2024. All rights reserved.