I made a MessageComposerView like this
import UIKit
protocol MessageComposerDelegate: NSObjectProtocol {
func messageDidChange(messageView: MessageComposerView, height: CGFloat)
func postMessage(message: String)
}
private let maxTextViewHeight: CGFloat = 100.0
class MessageComposerView: UIView, UITextViewDelegate {
#IBOutlet weak var textView: SAMTextView!
#IBOutlet weak var sendButton: UIButton!
weak var delegate:MessageComposerDelegate?
#IBAction func sendButtonAction(sender: UIButton) {
delegate?.postMessage(textView.text)
}
override func awakeFromNib() {
let borderColor = UIColor(white: 0.9, alpha: 1).CGColor
let layer = CALayer()
layer.backgroundColor = borderColor
layer.frame = CGRectMake(0, 0, CGRectGetWidth(UIScreen.mainScreen().bounds), 1.0)
self.layer.addSublayer(layer)
textView.backgroundColor = UIColor.whiteColor()
textView.layer.borderColor = borderColor
textView.layer.borderWidth = 1.0
textView.layer.cornerRadius = 5.0
textView.delegate = self
textView.layoutManager.allowsNonContiguousLayout = false
sendButton.backgroundColor = Color.Red.colorValue
sendButton.tintColor = UIColor.whiteColor()
sendButton.layer.cornerRadius = 5.0
}
//MARK: TextViewDelegate
func textViewDidChange(textView: UITextView) {
self.sendButton.enabled = !self.textView.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).isEmpty
textView.scrollEnabled = textView.contentSize.height >= maxTextViewHeight
let height = textView.scrollEnabled ? textView.contentSize.height : textView.intrinsicContentSize().height
delegate?.messageDidChange(self, height: min(height, maxTextViewHeight) + 16.0)
if let selectedTextRange = self.textView.selectedTextRange {
let caretRect = self.textView.caretRectForPosition(selectedTextRange.end);
let height = self.textView.textContainerInset.bottom + caretRect.size.height
self.textView.scrollRectToVisible(CGRectMake(caretRect.origin.x, caretRect.origin.y, caretRect.size.width, height), animated: true)
}
}
}
and in the ViewController when I increase the height of MessageComposerView:
func messageDidChange(messageView: MessageComposerView, height: CGFloat) {
messageView.bounds.size.height = height
self.reloadInputViews()
messageView.textView.reloadInputViews()
}
In iOS 9,It works well.
but in iOS 8.4,The textView and Button not change their frame rightly
So What should I do to fix it in iOS 8.4,Thank you!
Related
After upgrade on IOS 15 my previous code start works strange.
I have UITableView with cells with embedded views. When it loads in viewDidLoad cell's height constrain that I setup in storyboard become active and cell become close. Tap on cell makes height constraint become not active and cell open.
Height constraint for foldView
But in IOS 15 cell always open when loading. Even if height constraint is active.
here my code that makes it open or close:
var expanded: Bool = false {
didSet {
let duration = CATransaction.animationDuration()
UIView.animate(withDuration: duration) {
self.arrow.transform = self.expanded ? CGAffineTransform(rotationAngle: .pi / 2) : .identity
self.height.priority = .defaultHigh
self.height.isActive = !self.expanded
self.foldView.alpha = self.expanded ? 1 : 0
self.container.layoutIfNeeded()
}
}
}
and this is how I add embedded view:
func addEmbeddedView(_ view: UIView) {
self.foldView.subviews.forEach { $0.removeFromSuperview() }
self.foldView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
view.leadingAnchor.constraint(equalTo: self.foldView.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.foldView.trailingAnchor),
view.topAnchor.constraint(equalTo: self.foldView.topAnchor),
view.bottomAnchor.constraint(equalTo: self.foldView.bottomAnchor, constant: -9)
]
constraints[3].priority = .defaultHigh
NSLayoutConstraint.activate(constraints)
}
BUT! if I tap on cell from
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? TableViewCell else { return }
tableView.beginUpdates()
cell.expanded.toggle()
tableView.fixCellBounds()
tableView.endUpdates()
}
all works as expected and cell open and close in IOS 15 too.
Any suggestions what it could be?
As I assume in IOS 15 was some changes in AutoLayout that may affect my code..
Here my full custom cell class:
import UIKit
class CustomTableViewCell: UITableViewCell {
#IBOutlet weak var headerLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var arrowImage: UIImageView!
#IBOutlet weak var container: UIView!
#IBOutlet weak var foldView: UIView!
#IBOutlet weak var arrow: UIImageView!
let layer1 = CALayer(), layer2 = CALayer(), layer3 = CALayer()
var expanded: Bool = false {
didSet {
let duration = CATransaction.animationDuration()
UIView.animate(withDuration: duration) {
self.arrow.transform = self.expanded ? CGAffineTransform(rotationAngle: .pi / 2) : .identity
self.height.priority = .defaultHigh
self.height.isActive = !self.expanded
self.foldView.alpha = self.expanded ? 1 : 0
self.container.layoutIfNeeded()
}
}
}
#IBOutlet weak var height: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
self.expanded = false
container.layer.cornerRadius = 8
container.layer.cornerCurve = .continuous
container.backgroundColor = Colors_8_5.offWhite.color
self.contentView.backgroundColor = .clear
self.container.clipsToBounds = true
self.contentView.clipsToBounds = false
self.clipsToBounds = false
self.selectionStyle = .none
self.backgroundColor = .clear
[layer1, layer2, layer3].forEach {
$0.masksToBounds = false
$0.backgroundColor = UIColor.clear.cgColor
self.contentView.layer.insertSublayer($0, at: 0)
}
}
func configure(with model: CustomCellModel) {
self.headerLabel.attributedText = model.header
self.descriptionLabel.attributedText = model.text
self.descriptionLabel.isHidden = model.text == nil
}
override func setSelected(_ selected: Bool, animated: Bool) {
}
func addEmbeddedView(_ view: UIView) {
self.foldView.subviews.forEach { $0.removeFromSuperview() }
self.foldView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
view.leadingAnchor.constraint(equalTo: self.foldView.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.foldView.trailingAnchor),
view.topAnchor.constraint(equalTo: self.foldView.topAnchor),
view.bottomAnchor.constraint(equalTo: self.foldView.bottomAnchor, constant: -9)
]
constraints[3].priority = .defaultHigh
NSLayoutConstraint.activate(constraints)
}
override func layoutSubviews() {
super.layoutSubviews()
[layer1, layer2, layer3].forEach {
$0.frame = container.frame
}
layer1.CustomapplySketchShadow(color: .black, alpha: 0.04, x: 0, y: 4, blur: 8, spread: 0)
layer2.CustomapplySketchShadow(color: .black, alpha: 0.04, x: 0, y: 16, blur: 24, spread: 0)
layer3.CustomapplySketchShadow(color: .black, alpha: 0.04, x: 0, y: 24, blur: 32, spread: 0)
}
}
extension CALayer {
func CustomapplySketchShadow(
color: UIColor = .black,
alpha: Float = 0.2,
x: CGFloat = 0,
y: CGFloat = 2,
blur: CGFloat = 4,
spread: CGFloat = 0)
{
shadowColor = color.cgColor
shadowOpacity = alpha
shadowOffset = CGSize(width: x, height: y)
shadowRadius = blur / 2
if spread == 0 {
shadowPath = UIBezierPath(rect: self.bounds).cgPath
} else {
let dx = -spread
let rect = bounds.insetBy(dx: dx, dy: dx)
shadowPath = UIBezierPath(rect: rect).cgPath
}
}
}
I am trying to add corner radius on uitextfield effect applies but not sharp corner.
Please check attached pictures.
I am expecting result like this.
Here is my Code for gray textfield.
self.layer.cornerRadius = 7.5
self.layer.borderWidth = 1.5
self.layer.borderColor = UIColor(red: 209/255.0, green: 209/255.0, blue: 209/255.0, alpha: 1.0).CGColor
self.backgroundColor = UIColor.whiteColor()
Here is my Code for Red textfield.
self.layer.cornerRadius = 7.5
self.layer.borderWidth = 1.5
self.layer.borderColor = TextFieldRedBorderColor.CGColor
self.backgroundColor = TextFieldRedBackgroundColor
There is only color difference between both code but still it's not working.
self.layer.masksToBounds = true
This will solves your issue
#IBOutlet var passwordboarderview: UIView!
#IBOutlet var textusername: UITextField!
#IBOutlet var txtpassword: UITextField!
passwordboarderview.layer.cornerRadius = 7.5
passwordboarderview.layer.borderColor = UIColor.whiteColor().CGColor
passwordboarderview.layer.borderWidth = 2.0
passwordboarderview.clipsToBounds = true
txtpassword.attributedPlaceholder = NSAttributedString(string:"Password",attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
textusername.leftView = paddingView
textusername.leftViewMode = .Always
textusername.layer.borderWidth = 2.0
textusername.layer.cornerRadius = 7.5
textusername.layer.borderColor = UIColor.grayColor().CGColor
textusername.clipsToBounds = true
Output :
Storyboard:
//
// FDTextField.swift
// FilloutDocs
//
// Created by Janak Thakkar on 15/03/16.
// Copyright © 2016 zetrixweb. All rights reserved.
//
import UIKit
private var maxLengthDictionary = [UITextField : Int]()
#IBDesignable
class ZWTextField : UITextField {
var topBorder: UIView?
var bottomBorder: UIView?
var leftBorder: UIView?
var rightBorder: UIView?
var leftimageview : UIImageView?
var rightimageview : UIImageView?
#IBInspectable var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
#IBInspectable var ULText: Bool = false {
didSet {
let textRange = NSMakeRange(0, (self.text?.characters.count)!)
let attributedText = NSMutableAttributedString(string: (self.text)!)
attributedText.addAttribute(NSUnderlineStyleAttributeName , value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
#IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
#IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
#IBInspectable var fitToWidth: Bool = false {
didSet {
adjustsFontSizeToFitWidth = fitToWidth
}
}
#IBInspectable var cursorColor : UIColor = UIColor.blueColor(){
didSet {
tintColor = cursorColor
}
}
#IBInspectable var placeHolderColor : UIColor = UIColor.lightGrayColor(){
didSet {
setValue(placeHolderColor, forKeyPath: "_placeholderLabel.textColor")
}
}
override func layoutSubviews() {
super.layoutSubviews()
}
#IBInspectable var rightImage : UIImage? {
didSet {
if rightImage != nil {
let width = rightviewWidth > rightImage!.size.width + 10 ? rightviewWidth : rightImage!.size.width + 10
rightViewMode = UITextFieldViewMode.Always
rightimageview = UIImageView()
rightimageview!.frame=CGRectMake(self.frame.size.width - width, self.frame.origin.y+2, width,self.frame.size.height-4)
rightimageview!.image = rightImage
rightView = rightimageview
self.rightViewMode = .Always
rightimageview!.contentMode = .Center
}
else {
if rightimageview != nil {
rightimageview?.removeFromSuperview()
rightimageview = nil
}
}
}
}
#IBInspectable var rightviewWidth : CGFloat = 0 {
didSet{
if rightimageview != nil{
let width = rightviewWidth > rightImage!.size.width + 10 ? rightviewWidth : rightImage!.size.width + 10
rightimageview!.frame=CGRectMake(self.frame.origin.x+5, self.frame.origin.y+2, width,self.frame.size.height-4)
}
}
}
#IBInspectable var leftImage : UIImage? {
didSet {
if leftImage != nil {
let width = leftviewWidth > leftImage!.size.width + 10 ? leftviewWidth : leftImage!.size.width + 10
leftViewMode = UITextFieldViewMode.Always
leftimageview = UIImageView();
leftimageview!.frame=CGRectMake(self.frame.origin.x+50, self.frame.origin.y+5, width,self.frame.size.height-5)
//leftimageview!.frame = CGRectMake(10, 5, 40, 40)
leftimageview!.image = leftImage;
leftView = leftimageview;
self.leftViewMode = .Always
leftimageview!.contentMode = .Center
}
}
}
#IBInspectable var leftviewWidth : CGFloat = 0 {
didSet{
if leftimageview != nil{
let width = leftviewWidth > leftImage!.size.width + 10 ? leftviewWidth : leftImage!.size.width + 10
leftimageview!.frame=CGRectMake(self.frame.origin.x+5, self.frame.origin.y+2, width,self.frame.size.height-4)
}
}
}
#IBInspectable var bottomLineWidth : CGFloat = 1 {
didSet{
let border: CALayer = CALayer()
border.borderColor = UIColor.darkGrayColor().CGColor
self.frame = CGRectMake(0, self.frame.size.height - bottomLineWidth, self.frame.size.width, self.frame.size.height)
border.borderWidth = borderWidth
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}
#IBInspectable var bottomLineColor : UIColor = UIColor.lightGrayColor(){
didSet {
let border: CALayer = CALayer()
border.borderColor = bottomLineColor.CGColor
}
}
#IBInspectable var paddingLeft: CGFloat = 0
#IBInspectable var paddingRight: CGFloat = 0
override func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRectMake(bounds.origin.x + paddingLeft, bounds.origin.y,
bounds.size.width - paddingLeft - paddingRight, bounds.size.height);
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return textRectForBounds(bounds)
}
#IBInspectable var topBorderColor : UIColor = UIColor.clearColor()
#IBInspectable var topBorderHeight : CGFloat = 0 {
didSet{
if topBorder == nil{
topBorder = UIView()
topBorder?.backgroundColor=topBorderColor;
topBorder?.frame = CGRectMake(0, 0, self.frame.size.width, topBorderHeight)
addSubview(topBorder!)
}
}
}
#IBInspectable var bottomBorderColor : UIColor = UIColor.clearColor()
#IBInspectable var bottomBorderHeight : CGFloat = 0 {
didSet{
if bottomBorder == nil{
bottomBorder = UIView()
bottomBorder?.backgroundColor=bottomBorderColor;
bottomBorder?.frame = CGRectMake(0, self.frame.size.height - bottomBorderHeight, self.frame.size.width, bottomBorderHeight)
addSubview(bottomBorder!)
}
}
}
#IBInspectable var leftBorderColor : UIColor = UIColor.clearColor()
#IBInspectable var leftBorderHeight : CGFloat = 0 {
didSet{
if leftBorder == nil{
leftBorder = UIView()
leftBorder?.backgroundColor=leftBorderColor;
leftBorder?.frame = CGRectMake(0, 0, leftBorderHeight, self.frame.size.height)
addSubview(leftBorder!)
}
}
}
#IBInspectable var rightBorderColor : UIColor = UIColor.clearColor()
#IBInspectable var rightBorderHeight : CGFloat = 0 {
didSet{
if rightBorder == nil{
rightBorder = UIView()
rightBorder?.backgroundColor=topBorderColor;
rightBorder?.frame = CGRectMake(self.frame.size.width - rightBorderHeight, 0, rightBorderHeight, self.frame.size.height)
addSubview(rightBorder!)
}
}
}
#IBInspectable var maxLength: Int {
get {
if let length = maxLengthDictionary[self] {
return length
} else {
return Int.max
}
}
set {
maxLengthDictionary[self] = newValue
addTarget(self, action: "checkMaxLength:", forControlEvents: UIControlEvents.EditingChanged)
}
}
func checkMaxLength(sender: UITextField) {
let newText = sender.text
if newText?.characters.count > maxLength {
let cursorPosition = selectedTextRange
text = (newText! as NSString).substringWithRange(NSRange(location: 0, length: maxLength))
selectedTextRange = cursorPosition
}
}
}
Just add this file in project and you can set all the properties and can see realtime out.All properties you can set through storyboard.
There was just one mistake in my code.
TextField Border Style Was Line
textField.borderStyle = .Line
then I make it None
textField.borderStyle = .None
and it work like I wanted (Rounded Corners)...
Anyway.. Thanks for support and answers...
How can i implement UIScrollView when swiping snap to its subviews width. I need it to behave like pagingEnabled but i cant enable paging because i need my entire view can be swipe to scroll. if i do pagingEnable its impossible because scrollview bounds will be change to subviews width.
is there any possible way to do this.
please check the image for more details
import UIKit
class ViewController: UIViewController{
var navigationScroller: UIScrollView!
var contentScroller: UIScrollView!
var navContainer: UIView!
var contentContainer: UIView!
var selfWidth:CGFloat?
var navigationLabels = ["EVENTS", "MEMBERS", "SECTORS", "ORGANIZATIONS", "SEARCH", "EVENTS", "MEMBERS"]
private var buttonsTextFontAndSize: UIFont = UIFont(name: "HelveticaNeue-Light", size: 14)!
override func viewDidLoad() {
super.viewDidLoad()
selfWidth = self.view.frame.width
let frameWidth = self.view.frame.width
let frameHeight = self.view.frame.height
//let navscrollPosition = CGFloat( (frameWidth/2) - (75.0/2) )
navContainer = UIView(frame: CGRectMake(0.0, 75.0, frameWidth, 40.0))
navContainer.backgroundColor = UIColor(red:0, green:0.302, blue:0.522, alpha:1)
navigationScroller = UIScrollView(frame: CGRectMake(0.0, 0.0, frameWidth, 40.0))
navigationScroller.backgroundColor = UIColor.clearColor()
navigationScroller.pagingEnabled = false
navigationScroller.showsHorizontalScrollIndicator = false
navigationScroller.showsVerticalScrollIndicator = false
navigationScroller.clipsToBounds = false
navigationScroller.contentInset = UIEdgeInsetsZero
//navigationScroller.userInteractionEnabled = false
//navigationScroller.
addNavigationLabels(navigationScroller)
self.view.addSubview(navContainer)
navContainer.addSubview(navigationScroller)
navigationScroller.contentSize = CGSize(width: 150.0 * CGFloat(navigationLabels.count),height: 40.0)
navigationScroller.contentOffset = CGPoint(x: 170.0, y:0.0)
contentContainer = UIView(frame: CGRectMake(0.0, 115.0, frameWidth, frameHeight-115.0))
contentContainer.backgroundColor = UIColor.clearColor()
contentScroller = UIScrollView(frame: CGRectMake(0.0, 0.0, frameWidth, frameHeight-115.0))
contentScroller.backgroundColor = UIColor.clearColor()
contentScroller.pagingEnabled = true
contentScroller.showsHorizontalScrollIndicator = false
contentScroller.showsVerticalScrollIndicator = false
contentScroller.clipsToBounds = true
contentScroller.contentInset = UIEdgeInsetsZero
//contentScroller.addSubview(navContainer)
addContents(contentScroller)
self.view.addSubview(contentContainer)
contentContainer.addSubview(contentScroller)
contentScroller.contentSize = CGSize(width: frameWidth * CGFloat(navigationLabels.count),
height: frameHeight-115.0)
//contentScroller.delegate = self
navigationScroller.delegate = self
}
//MARK: -View Appeared function
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: -Adding navigation labels fron navigation labels array
private func addNavigationLabels(navScrollView:UIScrollView){
var buttonsXPosition: CGFloat = 0
var buttonNumber = 0
for navLabel in navigationLabels {
var navButton: UIButton!
let red = CGFloat(buttonNumber) - 0.9
let frameWidth = self.view.frame.width
navButton = UIButton(frame: CGRectMake(buttonsXPosition, 0, frameWidth/3, 40.0))
navButton.titleLabel!.font = buttonsTextFontAndSize
navButton.contentHorizontalAlignment = .Center
navButton.backgroundColor = UIColor(red:red , green:0.114, blue:0.286, alpha:1)
navButton.setTitle(navLabel, forState: UIControlState.Normal)
navButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
navScrollView.addSubview(navButton)
buttonsXPosition = frameWidth/3 + buttonsXPosition
buttonNumber++
}
}
func buttonAction(sender:UIButton!){
print("pressed")
}
// MARK: -Adding navigation labels fron navigation labels array
private func addContents(contentScroller:UIScrollView){
var buttonsXPosition: CGFloat = 0
var buttonNumber = 0
let frameWidth = self.view.frame.width
let frameHeight = self.view.frame.height
for navLabel in navigationLabels {
var navButton: UIButton!
navButton = UIButton(frame: CGRectMake(buttonsXPosition, 40.0, frameWidth, frameHeight-155))
navButton.titleLabel!.font = buttonsTextFontAndSize
navButton.contentHorizontalAlignment = .Center
navButton.backgroundColor = UIColor.darkGrayColor()
navButton.setTitle(navLabel, forState: UIControlState.Normal)
contentScroller.addSubview(navButton)
buttonsXPosition = frameWidth + buttonsXPosition
buttonNumber++
}
}
}
app view
You can implement UIScrollViewDelegate's method scrollViewWillEndDragging:withVelocity:targetContentOffset: and modify the offset at it will finish decelerating to match the width that you wish.
Something like this:
class ScrollSample: NSObject, UIScrollViewDelegate {
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let targetOffset = targetContentOffset.memory.x
// Round the offset to be a multiple of scrollview width
let roundedOffset = round(targetOffset / scrollView.frame.width) * scrollView.frame.width
targetContentOffset.memory = CGPoint(x: roundedOffset, y: 0)
}
}
any chance someone to help me in this code? it is a Slider that changes the size of the Fonts in a Label. this worked in IOS6 but I am trying to run on Swift 2.Thanks in advance.
import UIKit
class ViewController: UIViewController {
#IBAction func defaultSlider1(sender: UISlider) {
UISlider *slide = (UISlider *)sender;
int fonts = (int)(slide.value);
NSString *newtext = NSlog("%d", fonts);
label.font = [UIFont systemFontOfSize:fonts];
label.text = newtext;
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Please try following example (Demo):
import UIKit
class ViewController: UIViewController {
private var slider: UISlider!
private var label: UILabel!
private let minimumFontSize: Float = 16
private let maximumFontSize: Float = 48
override func viewDidLoad() {
super.viewDidLoad()
let width: CGFloat = view.bounds.width / 2
let height: CGFloat = 44.0
let size = CGSize(width: width, height: height)
let origin = CGPoint(x: self.view.center.x - (width / 2), y: self.view.center.y)
createSlider(origin, size: size)
createLabel(origin, size: size)
sliderAction()
}
func createSlider(origin: CGPoint, size: CGSize) {
let frame = CGRect(origin: origin, size: size)
self.slider = UISlider(frame: frame)
self.slider.addTarget(self,
action: Selector("sliderAction"),
forControlEvents: UIControlEvents.ValueChanged)
self.slider.minimumValue = minimumFontSize
self.slider.maximumValue = maximumFontSize
view.addSubview(self.slider)
}
func createLabel(origin: CGPoint, size: CGSize) {
let labelOrigin = CGPoint(x: origin.x, y: origin.y + size.height)
let frame = CGRect(origin: labelOrigin, size: size)
self.label = UILabel(frame: frame)
self.label.textAlignment = NSTextAlignment.Center
view.addSubview(self.label)
}
func sliderAction() {
let fontSize = CGFloat(self.slider.value)
self.label.font = UIFont.systemFontOfSize(fontSize)
self.label.text = "\(Int(fontSize))"
}
}
In case you're using Storyboards:
Add UISlider and UILabel to your View Controller Scene on the Storyboard
Insert #IBOutlets for each control (Ctrl+Drag from the control on the Storyboard to code, choose Outlet from Connection list)
Insert #IBAction for slider's Value Changed event (Ctrl+Drag from the slider control on the Storyboard to code, choose Action from Connection list)
You may end up with something like:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.slider.minimumValue = 16
self.slider.maximumValue = 48
self.sliderAction()
}
#IBAction func sliderValueChangedAction(sender: UISlider) {
self.sliderAction()
}
private func sliderAction() {
let fontSize = CGFloat(self.slider.value)
self.label.font = UIFont.systemFontOfSize(fontSize)
self.label.text = "\(Int(fontSize))"
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I am trying to create a Page View controller with numbers of view. I want a simple code sample that will use UIPageViewController.
import UIKit
class DummyVC: UIViewController, UIScrollViewDelegate {
let scrollView = UIScrollView(frame: CGRect(x:0, y:0, width:320,height: 300))
var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)
var pageControl : UIPageControl = UIPageControl(frame: CGRect(x:50,y: 300, width:200, height:50))
override func viewDidLoad() {
super.viewDidLoad()
configurePageControl()
scrollView.delegate = self
scrollView.isPagingEnabled = true
self.view.addSubview(scrollView)
for index in 0..<4 {
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
let subView = UIView(frame: frame)
subView.backgroundColor = colors[index]
self.scrollView .addSubview(subView)
}
self.scrollView.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)
pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
self.pageControl.numberOfPages = colors.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
}
For lazy coder this is the Swift 3 implementation based on That lazy iOS Guy 웃's answer
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
var pageControl : UIPageControl = UIPageControl(frame:CGRect(x: 50, y: 300, width: 200, height: 50))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configurePageControl()
scrollView.delegate = self
self.view.addSubview(scrollView)
for index in 0..<4 {
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
let subView = UIView(frame: frame)
subView.backgroundColor = colors[index]
self.scrollView .addSubview(subView)
}
self.scrollView.isPagingEnabled = true
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * 4, height: self.scrollView.frame.size.height)
pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
self.pageControl.numberOfPages = colors.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Swift 3 - Horizontal image scroll
import UIKit
class pageenabled: UIViewController,UIScrollViewDelegate
{
let imagelist = ["img1.jpg", "photo1.jpg", "photo3.jpg", "photo4.jpg", "photo5.jpg"]
var scrollView = UIScrollView()
var pageControl : UIPageControl = UIPageControl(frame:CGRect(x: 50, y: 300, width: 200, height: 50))
var yPosition:CGFloat = 0
var scrollViewContentSize:CGFloat=0;
override func viewDidLoad() {
super.viewDidLoad()
scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 300))
configurePageControl()
scrollView.delegate = self
self.view.addSubview(scrollView)
for i in stride(from: 0, to: imagelist.count, by: 1) {
var frame = CGRect.zero
frame.origin.x = self.scrollView.frame.size.width * CGFloat(i)
frame.origin.y = 0
frame.size = self.scrollView.frame.size
self.scrollView.isPagingEnabled = true
let myImage:UIImage = UIImage(named: imagelist[i])!
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.contentMode = UIViewContentMode.scaleAspectFit
myImageView.frame = frame
scrollView.addSubview(myImageView)
}
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * CGFloat(imagelist.count), height: self.scrollView.frame.size.height)
pageControl.addTarget(self, action: Selector(("changePage:")), for: UIControlEvents.valueChanged)
// Do any additional setup after loading the view.
}
func configurePageControl() {
// The total number of pages that are available is based on how many available colors we have.
self.pageControl.numberOfPages = imagelist.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.red
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
In Swift 3.0
craeate iboutlets through story board for scrollview and pagecontroller.
#IBOutlet weak var imgScrollView: UIScrollView!
#IBOutlet weak var imgPageController: UIPageControl!
var sliderImagesArray = NSMutableArray()
in viewdidload method write this code
sliderImagesArray = ["https://images.unsplash.com/photo-1432679963831-2dab49187847?w=1080","https://images.unsplash.com/photo-1447746249824-4be4e1b76d66?w=1080", "https://images.unsplash.com/photo-1463595373836-6e0b0a8ee322?w=1080"]
imgScrollView.delegate = self
for i in 0..<sliderImagesArray.count {
var imageView : UIImageView
let xOrigin = self.imgScrollView.frame.size.width * CGFloat(i)
imageView = UIImageView(frame: CGRect(x: xOrigin, y: 0, width: self.imgScrollView.frame.size.width, height: self.imgScrollView.frame.size.height))
imageView.isUserInteractionEnabled = true
let urlStr = sliderImagesArray.object(at: i)
print(imgScrollView,imageView, urlStr)
imageView.sd_setImage(with: URL(string: urlStr as! String), placeholderImage: UIImage(named: "placeholder.png"))
imageView .contentMode = UIViewContentMode.scaleToFill
self.imgScrollView.addSubview(imageView)
}
self.imgScrollView.isPagingEnabled = true
self.imgScrollView.bounces = false
self.imgScrollView.showsVerticalScrollIndicator = false
self.imgScrollView.showsHorizontalScrollIndicator = false
self.imgScrollView.contentSize = CGSize(width:
self.imgScrollView.frame.size.width * CGFloat(sliderImagesArray.count), height: self.imgScrollView.frame.size.height)
imgPageController.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
self.imgPageController.numberOfPages = sliderImagesArray.count
self.imgPageController.currentPage = 0
self.imgPageController.tintColor = UIColor.red
self.imgPageController.pageIndicatorTintColor = UIColor.black
self.imgPageController.currentPageIndicatorTintColor = UIColor.blue
after that implement scrollview delegate methods
func changePage(sender: AnyObject) -> () {
let x = CGFloat(imgPageController.currentPage) * imgScrollView.frame.size.width
imgScrollView.setContentOffset(CGPoint(x: x,y :0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(imgScrollView.contentOffset.x / imgScrollView.frame.size.width)
imgPageController.currentPage = Int(pageNumber)
}
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
#IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint!
extension ZoomedPhotoViewController: UIScrollViewDelegate {
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
}
private func updateMinZoomScaleForSize(size: CGSize) {
let widthScale = size.width / imageView.bounds.width
let heightScale = size.height / imageView.bounds.height
let minScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minScale
scrollView.zoomScale = minScale
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateMinZoomScaleForSize(view.bounds.size)
}
private func updateConstraintsForSize(size: CGSize) {
let yOffset = max(0, (size.height - imageView.frame.height) / 2)
imageViewTopConstraint.constant = yOffset
imageViewBottomConstraint.constant = yOffset
let xOffset = max(0, (size.width - imageView.frame.width) / 2)
imageViewLeadingConstraint.constant = xOffset
imageViewTrailingConstraint.constant = xOffset
view.layoutIfNeeded()
}
func scrollViewDidZoom(scrollView: UIScrollView) {
updateConstraintsForSize(view.bounds.size)
}
import UIKit
public class PhotoCommentViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var nameTextField: UITextField!
public var photoName: String!
override public func viewDidLoad() {
super.viewDidLoad()
if let photoName = photoName {
self.imageView.image = UIImage(named: photoName)
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let cell = sender as? UICollectionViewCell,
indexPath = collectionView?.indexPathForCell(cell),
photoCommentViewController = segue.destinationViewController as? PhotoCommentViewController {
photoCommentViewController.photoName = "photo\(indexPath.row + 1)"
}
}
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(PhotoCommentViewController.keyboardWillShow(_:)),
name: UIKeyboardWillShowNotification,
object: nil
)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(PhotoCommentViewController.keyboardWillHide(_:)),
name: UIKeyboardWillHideNotification,
object: nil
)
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) {
guard let value = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return }
let keyboardFrame = value.CGRectValue()
let adjustmentHeight = (CGRectGetHeight(keyboardFrame) + 20) * (show ? 1 : -1)
scrollView.contentInset.bottom += adjustmentHeight
scrollView.scrollIndicatorInsets.bottom += adjustmentHeight
}
func keyboardWillShow(notification: NSNotification) {
adjustInsetForKeyboardShow(true, notification: notification)
}
func keyboardWillHide(notification: NSNotification) {
adjustInsetForKeyboardShow(false, notification: notification)
}
#IBAction func hideKeyboard(sender: AnyObject) {
nameTextField.endEditing(true)
}
public var photoIndex: Int!
import UIKit
class ManagePageViewController: UIPageViewController {
var photos = ["photo1", "photo2", "photo3", "photo4", "photo5"]
var currentIndex: Int!
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
// 1
if let viewController = viewPhotoCommentController(currentIndex ?? 0) {
let viewControllers = [viewController]
// 2
setViewControllers(
viewControllers,
direction: .Forward,
animated: false,
completion: nil
)
}
}
func viewPhotoCommentController(index: Int) -> PhotoCommentViewController? {
if let storyboard = storyboard,
page = storyboard.instantiateViewControllerWithIdentifier("PhotoCommentViewController")
as? PhotoCommentViewController {
page.photoName = photos[index]
page.photoIndex = index
return page
}
return nil
}
}