2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

選択時にセパレータが消えないUITableViewCell

Last updated at Posted at 2014-11-13

iOS7以降のUITableViewCellはセルの選択時に上下のセパレータが消えます。
なので消えないようなカスタムセルを作りました。
iOS7とiOS8で確認しました。SingleLineしか動かないかも。

import UIKit

class SeparatorVisibleCell: UITableViewCell {

	required init(coder aDecoder: NSCoder) {
		super.init(coder: aDecoder)
	}
	
	private lazy var separatorNotificationName = "CellSeparatorNotification"
	private var registered = false
	private lazy var separatorHeight: CGFloat = {
		return 1.0 / UIScreen.mainScreen().scale
		/*
		for v in self.contentView.superview!.subviews as [UIView] {
			println("setShowsSeparator: \(NSStringFromClass(v.dynamicType))")
			if NSStringFromClass(v.dynamicType).hasSuffix("SeparatorView") {
				return v.frame.size.height
			}
		}
		abort()
		return 1.0 / UIScreen.mainScreen().scale
		*/
	}()
	
	deinit {
		if registered {
			NSNotificationCenter.defaultCenter().removeObserver(self, name: separatorNotificationName, object: nil)
		}
	}
	
	override func layoutSubviews() {
		super.layoutSubviews()
		
		if !registered {
			NSNotificationCenter.defaultCenter().addObserver(self, selector: "separatorNotification:", name: separatorNotificationName, object: nil)
			registered = true
		}
		
		if let bg = selectedBackgroundView {
			var r = frame
			r.origin = CGPointMake(0, separatorHeight)
			r.size.height -= separatorHeight
			bg.frame = r
		}
	}
		
	override func setHighlighted(highlighted: Bool, animated: Bool) {
		super.setHighlighted(highlighted, animated: animated)
		setShowsSeparator()
		NSNotificationCenter.defaultCenter().postNotificationName(separatorNotificationName, object: self, userInfo: ["max_y": CGRectGetMinY(frame)])
	}
	
	private func setShowsSeparator() {
		println("setShowsSeparator: \(NSStringFromCGRect(frame))")
		for v in contentView.superview!.subviews as [UIView] {
			println("setShowsSeparator: \(NSStringFromClass(v.dynamicType))")
			if NSStringFromClass(v.dynamicType).hasSuffix("SeparatorView") {
				v.hidden = false
			}
		}
	}
	
	func separatorNotification(notif: NSNotification) {
		var y = notif.userInfo?["max_y"] as CGFloat
		
		println("separatorNotification: \(y), \(NSStringFromCGRect(self.frame)) -> \(abs(CGRectGetMaxY(frame) - y))")
		if abs(CGRectGetMaxY(frame) - y) < 1 {
			setShowsSeparator()
		}
	}
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?