Swift - 标签角在tableviewcell中具有不同的半径

时间:2017-05-01 06:49:34

标签: ios swift uitableview

我有一个带标签的tableView单元格 我想制作带角半径的标签 我知道这样称呼函数:

label.layer.cornerRadius = 6

带角落的标签如下:

半径

But I want to let three corners have
所以,我找到了这个功能。

func roundCorners(corners:UIRectCorner, radius: CGFloat) {
    let mask = CAShapeLayer()
    mask.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
    layer.mask = mask
}

但我称这个功能标签消失了 我的表格查看单元格有什么问题。

标签消失:

enter image description here

我的代码:

class ContentLabel:UILabel {

    override init(frame: CGRect) {
        super.init(frame:frame)
        translatesAutoresizingMaskIntoConstraints = false
        numberOfLines = 0
        isUserInteractionEnabled = true
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func drawText(in rect: CGRect) {
        let insets: UIEdgeInsets = UIEdgeInsets(top: defaultContentPadding, left: defaultPadding, bottom: defaultContentPadding, right: defaultPadding)
        super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }

    class TableViewCell: UITableViewCell {

        var labelView:UILabel = { ()->UILabel in

            let label:UILabel = ContentLabel()
            label.translatesAutoresizingMaskIntoConstraints = false
            label.numberOfLines = 0
            label.lineBreakMode = NSLineBreakMode.byCharWrapping

            //label.layer.cornerRadius = 6  
            label.roundCorners(corners: [.topLeft,.topRight,.bottomLeft], radius: 6) 

            //What's wrong here!!!!!!!
            label.layer.masksToBounds = true
            return label
        }() 

        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            loadView()
        }

        func loadView() {
            contentView.addSubview(labelView)
        }

        override func layoutSubviews() {
            super.layoutSubviews()
            loadConstraints()
        }

        func loadConstraints() {
            let labelViewWidth:CGFloat = contentView.bounds.width*0.6
            labelView.frame = CGRect(x: 0, y: 0, width: labelViewWidth, height: CGFloat.greatestFiniteMagnitude)
            labelView.sizeToFit()

            let views = DictionaryOfInstanceVariables(self, objects: "labelView","icon")
            let metrics = ["padding":10]

            addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[labelView]-padding-[icon]-padding-|", options: [], metrics: metrics, views: views))
        }
    }

我也尝试在func layoutSubviews()中添加代码,我成功地改变了角落,但是当我滚动tableview时,单元格内容消失了,滚动非常迟缓。

1 个答案:

答案 0 :(得分:0)

试试这个:

在storyboard中将约束应用于标签(如果添加,则为w.r.to单元格视图):

  1. 顶部布局,
  2. 领导,
  3. 图像之间的水平间距。