【问题标题】:Add border for view not working for ipad为视图添加边框不适用于 ipad
【发布时间】:2016-03-09 20:23:41
【问题描述】:

我根据这个答案创建了扩展:How to add a border just on the top side of a UIView

extension CALayer {

    func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
        //https://stackoverflow.com/questions/17355280/how-to-add-a-border-just-on-the-top-side-of-a-uiview
        let border = CALayer()

        switch edge {
        case UIRectEdge.Top:
            border.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), thickness)
            break
        case UIRectEdge.Bottom:
            border.frame = CGRectMake(0, CGRectGetHeight(self.frame) - thickness, CGRectGetWidth(self.frame), thickness)
            break
        case UIRectEdge.Left:
            border.frame = CGRectMake(0, 0, thickness, CGRectGetHeight(self.frame))
            break
        case UIRectEdge.Right:
            border.frame = CGRectMake(CGRectGetWidth(self.frame) - thickness, 0, thickness, CGRectGetHeight(self.frame))
            break
        default:
            break
        }

        border.backgroundColor = color.CGColor;

        self.addSublayer(border)
    }
}

但在 Ipad 中我只看到 70% 的边框宽度:

我尝试将frame 更改为bounds,但也没有成功。

【问题讨论】:

  • 代码对我来说看起来不错,1-您是在模拟器中放大还是缩小?这可能会压缩一些像素,2-您是否还有另一个可以覆盖右侧该部分的白色区域的对象?
  • 我在真机上也试过了,一样。但在 iphone 上可以。

标签: ios swift


【解决方案1】:

添加边框后调整视图的大小。您在 viewDidLoad() 方法中添加边框对吗?尝试在 viewDidAppear() 方法中添加边框:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    yourView.layer.addBorder(UIRectEdge.Top, color: UIColor.redColor(), thickness: 0.5)
}

移动添加层
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {}

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.layer.addBorder(UIRectEdge.Top, color: UIColor.redColor(), thickness: 0.5)
}

【讨论】:

  • 我也在表格单元格中使用这种方法
  • 您在 cellForRow 方法中使用它对吗?检查该单元格的框架。在控制台打印下一个值: print("cell width = \ (cell.frame.size.width)") 和 print("view width = \ (view.frame.size.width)") in cellForRow 方法我认为你的看法实际上比单元框宽。最好将方法从 cellForRow 移动到 UITableViewDelegate 的 willDisplayCell 方法
  • @Arti 您能否接受作为最终答案,这样我会获得更多声誉)我是新来的,希望能够发表评论,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多