Does anyone know how to get a custom section header/footer view from blinking on reload of a section?
Section(header:"",footer:"") {section in
section.tag = "main"
var header = HeaderFooterView<GenericSection>(HeaderFooterProvider.Class)
header.onSetupView = { v,s in
v.label.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width - 30, height: 20 )
v.label.text = self.row.title
v.label.numberOfLines = 0
v.label.textAlignment = .Justified
v.label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
v.label.textColor = UIColor(red:0.47, green:0.47, blue:0.49, alpha:1.0)
v.label.frame = v.label.bounds
v.label.sizeToFit()
v.bounds = CGRect(x: -8, y: -8, width: v.label.bounds.width - 15, height: v.label.bounds.height + 25)
}
section.header = header
section.footer = nil
}
If I use Section(header:"test",footer:"test2") the header view never blinks on any form modifications which is what I want. However, I am using a custom margins and adding icons to the headers which is why I need custom views to serve as the header/footer. Is there a property that I am not setting on the .onSetupView that would resolve this?
your problem is related to your header view reload over and over again, and adjust his frame over and over again, so you can fix this simply adding a bool variable like this
With issue
Without issue
class GenericSection: UIView {
let label = UILabel()
var positioned = false
override init(frame: CGRect) {
super.init(frame: frame)
label.frame = CGRect(x: 0,y: 0,width: self.bounds.size.width - 30, height: 40)
self.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
and then
form +++ Section(header:"",footer:"") {section in
section.tag = "main"
var header = HeaderFooterView<GenericSection>(HeaderFooterProvider.Class)
header.onSetupView = { v,s in
if(!v.positioned)
{
v.layer.borderColor = UIColor.redColor().CGColor
v.layer.borderWidth = 1
v.label.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width - 30, height: 20 )
v.label.text = "Testing Custom Header without issue"
v.label.numberOfLines = 0
v.label.textAlignment = .Justified
v.label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
v.label.textColor = UIColor(red:0.47, green:0.47, blue:0.49, alpha:1.0)
v.label.frame = v.label.bounds
v.label.sizeToFit()
v.bounds = CGRect(x: -8, y: -8, width: v.label.bounds.width - 15, height: v.label.bounds.height + 25)
v.setNeedsLayout()
v.setNeedsDisplay()
v.positioned = true
}
}
section.header = header
section.footer = nil
}
I hope this helps you, regards
Related
this is the code where i am configuring the cell.
cell.configure(image: models[indexPath.item].image, tagText: models[indexPath.item].tag, priceIcon: models[indexPath.item].priceIcon, value: models[indexPath.item].price)
and this is my code for cell.
//
// ImageCollectionViewCell.swift
// tr0ve-iOSApp
//
//
//
// ImageCollectionViewCell.swift
// MyCollectionView
//
import UIKit
class ImageCollectionViewCell: UICollectionViewCell {
static let identifier = "ImageCollectionViewCell"
let itemView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(itemView)
contentView.clipsToBounds = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
itemView.frame = contentView.bounds
}
override func prepareForReuse() {
super.prepareForReuse()
itemView.subviews.forEach { view in
view.removeFromSuperview()
}
}
func configure (image: UIImage?, tagText: String, priceIcon: UIImage, value: Float){
let imageView = UIImageView(image: image)
let priceTagView = UIView(frame: CGRect(x: 5, y: contentView.frame.size.height-50, width: 60, height: 20))
priceTagView.backgroundColor = .black
let valueLabel = UILabel(frame: CGRect(x: 20, y: 5, width: 35, height: 10))
valueLabel.textColor = .white
valueLabel.text = String(value)
valueLabel.font = UIFont.systemFont(ofSize: 12, weight: .regular)
let priceIconView = UIImageView(frame: CGRect(x: 5, y: 5, width: 10, height: 10))
priceIconView.image = priceIcon
priceTagView.addSubview(priceIconView)
priceTagView.addSubview(valueLabel)
let tag = UILabel(frame: CGRect(x: 100, y: contentView.frame.size.height-50, width: 20, height: 20))
tag.text = tagText
tag.textColor = .white
tag.textAlignment = .center
if tagText == "UC" {
tag.backgroundColor = .green
}
else {
tag.backgroundColor = .blue
}
itemView.addSubview(imageView)
itemView.addSubview(priceTagView)
itemView.addSubview(tag)
}
}
[in this image i want to add subview in cell's bottom, and in tried it using image's frame and by contentView's frame. but it is doing good for some cells and bad for the other ones. and when i scroll everyhing meshes up.1
This question already has answers here:
Add padding between label and its border
(4 answers)
Closed 8 months ago.
I have created a text programmatically with a grey background using UILabel.
Now I would like to add padding to this paragraph/text. Also, it would be great if you could show me how to add margin to my UILabel as well.
import UIKit
final class SignUpViewController: UIViewController {
public let identifier = "Sign Up"
private let logoImage : UIImageView = {
let imageView = UIImageView()
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFit
imageView.image = UIImage(named: "MyLogoWithTitle")
imageView.clipsToBounds = true
return imageView
}()
private let instructionText : UILabel = {
let label = UILabel()
label.text = "Please read terms and conditions below carefully before proceeding with the registration."
label.backgroundColor = UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4)
label.numberOfLines = 0
label.tintColor = .white
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(logoImage)
view.addSubview(instructionText)
view.backgroundColor = UIColor().colorFromHex(hex: "#141920", opacity: 1.0)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
logoImage.frame = CGRect(x: 0,
y: 0,
width: 140,
height: 60)
logoImage.center = CGPoint(x: view.center.x, y: view.height/5)
instructionText.frame = CGRect(
x: 5,
y: 5 + logoImage.bottom,
width: view.width - 20,
height: 50)
.integral
instructionText.layer.cornerRadius = 10
}
}
Notice that I created an extension to UIColor so that I can input hex color in this way - UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4) .
I am looking forward to hearing from you. Thank you.
You can insert this UILabel into the container (any UIView) and set its position inside.
But the simplest trick is to use UIButton instead of UILabel. You can configure UIEdgeInsets for padding.
So that UIButton does not act as a button simply set button.isUserInteractionEnabled = false.
By default, text in the button are placed in the center, but its position is easy to change with contentHorizontalAlignment and contentVerticalAlignment
And as a bonus, you can add icons right near to the text. :)
UPD.
Could you give me a simple example? I tried that way but I didn't get the result I expected. – Punreach Rany
let buttonUsedAsLabel = UIButton()
// Your question was about padding
// It's it!
buttonUsedAsLabel.titleEdgeInsets = UIEdgeInsets(top: 5, left: 20, bottom: 5, right: 20)
// Make it not user interactable as UILabel is
buttonUsedAsLabel.isUserInteractionEnabled = false
// set any other properties
buttonUsedAsLabel.setTitleColor(.white, for: .normal)
buttonUsedAsLabel.contentVerticalAlignment = .top
buttonUsedAsLabel.contentHorizontalAlignment = .left
// Set title propeties AFTER it was created with text because it's nullable
// You can use attributed title also
// Never use any (button.titleLabel) before its creation
// for example: (button.titleLabel?.text = "zzz") do nothing here
buttonUsedAsLabel.setTitle("This is the text", for: .normal)
buttonUsedAsLabel.titleLabel?.font = .systemFont(ofSize: 20, weight: .medium)
buttonUsedAsLabel.titleLabel?.numberOfLines = 0
buttonUsedAsLabel.titleLabel?.lineBreakMode = .byWordWrapping
// and so on
// ...
// This is the triсk :)
Of course, you can do it with a storyboard if prefer.
1. Add this class
PaddingLabel.swift
import UIKit
class PaddingLabel: UILabel {
var edgeInset: UIEdgeInsets = .zero
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: edgeInset.top, left: edgeInset.left, bottom: edgeInset.bottom, right: edgeInset.right)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + edgeInset.left + edgeInset.right, height: size.height + edgeInset.top + edgeInset.bottom)
}
}
2. Add this code to your ViewController
let label = PaddingLabel()
override func viewDidLoad() {
super.viewDidLoad()
label.backgroundColor = UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4)
//Setting the padding label
label.edgeInset = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
}
The answer to the link below is that I wrote the same content based on the storyboard.
Add padding between label and its border
I use textfield. Set padding and text in textfield. And do not allow editing.
extension UITextField {
func addLeftPadding() {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: self.frame.height))
self.leftView = paddingView
self.leftViewMode = ViewMode.always
}
}
//ViewController
#IBOutlet weak var myTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
myTextField.addLeftPadding()
myTextField.isUserInteractionEnabled = false
myTextField.text = "your label text"
}
I have a UIView with a UIButton inside it but the button does not recognise gestures
Any ideas why? I have tried using the solutions in the questions related to this but have not succeeded.
The whole class code:
import UIKit
import Foundation
public class HUDView: UIView , UIGestureRecognizerDelegate {
var stopwatch: StopwatchView
var gamePoints: CounterLabelView
var hintButton: UIButton!
required public init(coder aDecoder: NSCoder) {
fatalError("Never call this... Use init(frame:)")
}
override init(frame: CGRect) {
self.stopwatch = StopwatchView(frame: CGRect(x: ScreenWidth/2 - 150, y: 0, width: 300, height: 100))
self.stopwatch.setSecondsRemaining(0)
self.gamePoints = CounterLabelView(font: FontHUD!, frame: CGRect(x: ScreenWidth - 200, y: 30, width: 320, height: 70))
gamePoints.textColor = UIColor.black
gamePoints.value = 0
super.init(frame: frame)
self.addSubview(gamePoints)
let pointsLabel = UILabel(frame: CGRect(x: ScreenWidth - 340, y: 30, width: 140, height: 70))
pointsLabel.backgroundColor = UIColor.clear
pointsLabel.font = FontHUD
pointsLabel.text = " Points:"
self.addSubview(pointsLabel)
self.isUserInteractionEnabled = false
self.addSubview(self.stopwatch)
//load the button image
let hintButtonImage = UIImage(named: "btn")!
//the help button
self.hintButton = UIButton()
// hintButton.perform(#selector(HUDView.s))
hintButton.setTitle("Hint!", for:.normal)
hintButton.titleLabel?.font = lHud
hintButton.setBackgroundImage(hintButtonImage, for: .normal)
hintButton.frame = CGRect(x: 50, y: 30, width: hintButtonImage.size.width, height: hintButtonImage.size.height)
// hintButton.center = self.center
//50, 30, hintButtonImage.size.width, hintButtonImage.size.height
hintButton.alpha = 1.0
hintButton.isUserInteractionEnabled = true
self.addSubview(hintButton)
// hintButton.addTarget(self, action: #selector(self.tapButton(_:)), for: .touchUpInside)
let g = UITapGestureRecognizer(target: self, action: #selector(self.h(_:)))
g.delegate = self
hintButton.addGestureRecognizer(g)
}
func h(_ sender: UITapGestureRecognizer) {
print("hey!")
fatalError()
}
}
The problem is in line self.isUserInteractionEnabled = false
You are adding button as a subview to HUDView. The button tap will not work because the parent view ie:HUDView has user interaction disabled and so the user interaction of all the subViews will be disabled.
Make the changes as self.isUserInteractionEnabled = true it will work.
I'm writing my first iOS app and I wanna just answer what is the best-known solution to make this? It's simple tag collection. I have already looked over the Internet but I have found nothing. I think the best way is to make my own structure of buttons maybe?
Here is what I want to achieve:
sometimes you need do it yourself:
import UIKit
import PlaygroundSupport
class TagsView: UIView {
// MARK: - Properties
var offset: CGFloat = 5
// MARK: - Public functions
func create(cloud tags: [UIButton]) {
var x = offset
var y = offset
for (index, tag) in tags.enumerated() {
tag.frame = CGRect(x: x, y: y, width: tag.frame.width, height: tag.frame.height)
x += tag.frame.width + offset
let nextTag = index <= tags.count - 2 ? tags[index + 1] : tags[index]
let nextTagWidth = nextTag.frame.width + offset
if x + nextTagWidth > frame.width {
x = offset
y += tag.frame.height + offset
}
addSubview(tag)
}
}
}
private func button(with title: String) -> UIButton {
let font = UIFont.preferredFont(forTextStyle: .headline)
let attributes: [NSAttributedString.Key: Any] = [.font: font]
let size = title.size(withAttributes: attributes)
let button = UIButton(type: .custom)
button.setTitle(title, for: .normal)
button.titleLabel?.font = font
button.setTitleColor(.darkGray, for: .normal)
button.layer.borderWidth = 1.0
button.layer.cornerRadius = size.height / 2
button.layer.borderColor = UIColor.darkGray.cgColor
button.frame = CGRect(x: 0.0, y: 0.0, width: size.width + 10.0, height: size.height + 10.0)
button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 5.0)
return button
}
let titles = ["Freedom", "God", "Happiness", "Imagination", "Intelligence", "Other"]
let tags = titles.map { button(with: $0) }
let frame = CGRect(x: 0, y: 0, width: 260, height: 200)
let tagsView = TagsView(frame: frame)
tagsView.backgroundColor = .white
tagsView.create(cloud: tags)
PlaygroundPage.current.liveView = tagsView
PlaygroundPage.current.needsIndefiniteExecution = true
I resolve this problem, using collection view.
class FilterController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
#IBOutlet var collectionView: UICollectionView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 150, left: 10, bottom: 150, right: 10)
// layout.itemSize = CGSize(width: 90, height: 45)
layout.itemSize = CGSizeFromString("Aloha")
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView!.dataSource = self
collectionView!.delegate = self
collectionView!.registerClass(TagCell.self, forCellWithReuseIdentifier: "TagCell")
collectionView!.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView!)
}
Just dynamically add buttons to the superView, and change the background as per your requirement.
I am trying to access the MyCustomView from another class using the following code in ViewController.swift ..
var view = MyCustomView(frame: CGRectZero)
.. in the viewDidLoad method. The problem is the view does not get initialized in the simulator.
I have already set class in storyboard for the current ViewController.
class MyCustomView: UIView {
var label: UILabel = UILabel()
var myNames = ["dipen","laxu","anis","aakash","santosh","raaa","ggdds","house"]
override init(){
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addCustomView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addCustomView() {
label.frame = CGRectMake(50, 10, 200, 100)
label.backgroundColor=UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label.text = "test label"
label.hidden=true
self.addSubview(label)
var btn: UIButton = UIButton()
btn.frame=CGRectMake(50, 120, 200, 100)
btn.backgroundColor=UIColor.redColor()
btn.setTitle("button", forState: UIControlState.Normal)
btn.addTarget(self, action: "changeLabel", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(btn)
var txtField : UITextField = UITextField()
txtField.frame = CGRectMake(50, 250, 100,50)
txtField.backgroundColor = UIColor.grayColor()
self.addSubview(txtField)
}
The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.
But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:
customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)
Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.
Swift 3 / Swift 4 Update:
let screenSize: CGRect = UIScreen.main.bounds
let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width - 10, height: 10))
self.view.addSubview(myView)
var customView = UIView()
#IBAction func drawView(_ sender: AnyObject) {
customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
customView.backgroundColor = UIColor.black //give color to the view
customView.center = self.view.center
self.view.addSubview(customView)
}
let viewDemo = UIView()
viewDemo.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
self.view.addSubview(viewDemo)
view = MyCustomView(frame: CGRectZero)
In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.