Performing a segue from a button called from NSObject - ios

I have 2 ViewControllers :
1) MainViewController
2) WebViewController
and a segue with identifier ShowWeb.
MainViewController Contain Multiple NSObjects instances initiated from one class Name AppView: NSObject
inside each NSObject there is a UIButton that I want it to perform the segue of type show.
How to perform the segue?
sorry if my question is repeated but i searched yesterday for about 4 hours all the site and didn't find the exact manner, and to know I am using swift.
I Will explain more clearly:
class MainViewController: {
var appviews = [AppView]()
override func viewDidLoad() {
super.viewDidLoad()
for i = 0; i < MyApps.count ; ++i{
var appview = AppView()
appview = AppView(sourceView: AppsScrollView, AppIconURLString: AppPicture,AppName: "MyAppName", LoadedDescription:"Very Good Application", ObjectNo: i, LinkButtonString: "http://stackoverflow.com/posts/28288611")
appviews.append(appview)
}
}
//
// AppView.swift
// Arabic Apps
//
// Created by d-point on 3/24/1436 AH.
// Copyright (c) 1436 e-Dever. All rights reserved.
//
import UIKit
class AppView: NSObject {
var BackView = UIView()
var AppIconView = UIImageView()
var TitleLabel = UILabel()
var DescriptionLabel = UILabel()
var LinkIcon = UIImageView()
var AppNo:Int!
var DescriptionText:String!
var AppTitleName:String!
let originView:UIView!
let LinkImage = UIImage(named: "HyperLink.png")
var LinkButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
let TitleHeight:CGFloat = 20.0
let DescHeight:CGFloat = 40.0
let BackViewHeight:CGFloat = 100.0
let AppIconSize:CGFloat = 80.0
let Inset:CGFloat = 10.0
let BackgroundAlpha:CGFloat = 0.5
let LinkButtonSize:CGFloat = 35.0
var LinkButtonPath = String()
var MyViewController = UIViewController()
override init() {
super.init ()
}
init(sourceView:UIView, AppIconURLString: String? , AppName: String,LoadedDescription: String , ObjectNo: Int , LinkButtonString: NSString){
super.init()
originView = sourceView
AppIconView.image = UIImage(named: "App-Icon-Copy.png")
if var Icon = AppIconURLString {
ImagesLoader.downloadImage(NSURL(string: Icon), handler: {image, error in
self.AppIconView.image = image
})}
AppTitleName = AppName
DescriptionText = LoadedDescription
AppNo = ObjectNo
LinkButtonPath = LinkButtonString
setupAppView()
}
func setupAppView() {
//SetupBackView
BackView.frame = CGRectMake(Inset,
Inset + (CGFloat(AppNo) * (BackViewHeight + 15)),
originView.bounds.size.width - (Inset * 2),
BackViewHeight)
BackView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(BackgroundAlpha)
BackView.layer.cornerRadius = 20.0
BackView.clipsToBounds = false
originView.addSubview(BackView)
//SetupAppIconView
AppIconView.frame = CGRectMake(BackView.bounds.size.width - AppIconSize - Inset, Inset, AppIconSize, AppIconSize)
AppIconView.layer.cornerRadius = 15.0
AppIconView.layer.borderWidth = 2.0
AppIconView.layer.borderColor = UIColor.whiteColor().CGColor
AppIconView.clipsToBounds = true
BackView.addSubview(AppIconView)
//SetupTitleView
TitleLabel.frame = CGRectMake(Inset, Inset, BackView.bounds.size.width - AppIconSize - Inset*6, TitleHeight)
TitleLabel.text = AppTitleName
TitleLabel.textColor = UIColor.blackColor()
TitleLabel.textAlignment = NSTextAlignment.Center
//TitleLabel.font = UIFont(name: TitleLabel.font.fontName, size: 18.0)
TitleLabel.font = UIFont.boldSystemFontOfSize(16.0)
BackView.addSubview(TitleLabel)
//SetupDescriptionLabel
DescriptionLabel.frame = CGRectMake(Inset, TitleHeight, BackView.bounds.size.width - AppIconSize - Inset*6, DescHeight)
DescriptionLabel.text = DescriptionText
DescriptionLabel.textColor = UIColor.blackColor()
DescriptionLabel.textAlignment = NSTextAlignment.Justified
BackView.addSubview(DescriptionLabel)
//SetupButtonView
//LinkButton
LinkButton.frame = BackView.bounds
LinkButton.addTarget(self, action:"GotoLinkURL:", forControlEvents:UIControlEvents.TouchUpInside)
LinkButton.tag = AppNo
BackView.addSubview(LinkButton)
}
func GotoLinkURL(sender:UIButton) {
var mainviewcontroller:MainViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MainView") as MainViewController
mainviewcontroller.performSegueWithIdentifier("ShowWeb", sender: self)
}
}

Related

UITapGestureRecognizer doesn't work properly

I made the function updateItems() which create, from an array, many UIView's in a UIScrollView :
Here is the file where this function is :
class MainViewController: UIViewController {
#IBOutlet weak var body: UIScrollView!
#IBOutlet weak var edit: UIButton!
var _title: String = "Title"
var _isEditing: Bool = false
var firstItems: [UISectionView] = []
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationBar.topItem?.title = self._title
navigationController?.navigationItem.largeTitleDisplayMode = .automatic
body.contentSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height + 100)
self.updateItems(self.firstItems)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func updateItems(_ s: [UISectionView]) {
let topMargin = 10
let rightMargin = 10
let leftMargin = 10
let space = 5
let heightItem = 60
var b = topMargin
for i in body.subviews {
i.removeFromSuperview()
}
for t in s {
if t.isHidden == true {
continue
}
if t.title != nil {
let f = UIFont(name: "Helvetica", size: 20)
let l = UILabel(frame: CGRect(x: rightMargin, y : b, width: Int(UIScreen.main.bounds.width) - (rightMargin + leftMargin), height: Int(f!.lineHeight)))
l.font = f
l.text = t.title
body.addSubview(l)
b = b + Int(f!.lineHeight) + space
}
for i in t.items{
body.addSubview(i.getView(frame: CGRect(x: rightMargin, y: b, width: Int(UIScreen.main.bounds.width) - (rightMargin + leftMargin), height: heightItem), view: self))
b = b + heightItem + space
}
}
}
}
TIPS : UISectionView is an object which contains an array of UIItemView
The object UIItemView looks like :
class UIItemView {
var icon: UIImage = UIImage();
var line1: rString = rString("")!;
var line2: rString = rString("")!;
var leftline: Any = String();
var background: String = "white"
var onItemTap: (_ sender: UITapGestureRecognizer?) -> () = {sender in }
var onItemLongPress: (_ sender: UILongPressGestureRecognizer?) -> () = {sender in }
var id: String
init?(_ id: String) {
self.id = id
}
public func getView(frame: CGRect, view: UIViewController) -> UIView {
let width = Int(frame.width)
let height = Int(frame.height)
let rightMargin = 20
let leftMargin = 10
let topMargin = 10
let bottomMargin = 10
let iconSide = height - (topMargin + bottomMargin)
let marginLine = leftMargin + iconSide + 10
let v = UIView(frame: frame)
//Background & shape
if self.background == "white" {
v.backgroundColor = UIColor.white;
} else if self.background == "blur" {
let bEV = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.extraLight))
bEV.frame = v.bounds
bEV.autoresizingMask = [.flexibleWidth, .flexibleHeight]
v.addSubview(bEV)
}
v.layer.cornerRadius = 10.0
//Icon
let i = UIImageView()
i.image = self.icon;
i.frame = CGRect(x: leftMargin, y: topMargin, width: iconSide, height: iconSide)
v.addSubview(i)
//First Line
let l1 = self.line1.getLabel()
l1.frame = CGRect(x: marginLine, y: topMargin, width: width - (marginLine + leftMargin), height: Int(self.line1.getFont().lineHeight))
v.addSubview(l1)
//Seconde Line
let l2 = self.line2.getLabel()
l2.frame = CGRect(x: marginLine, y: height - (bottomMargin + Int(self.line1.getFont().lineHeight)), width: width - (marginLine + leftMargin), height: Int(self.line1.getFont().lineHeight))
v.addSubview(l2)
//Left Line
if type(of: self.leftline) == type(of: SpinnerView()) {
let sv = (self.leftline as! SpinnerView)
sv.frame = CGRect(x: width - (rightMargin + iconSide), y: height/2 - iconSide/2, width: iconSide, height: iconSide)
v.addSubview(sv)
} else if type(of: self.leftline) == type(of: rString("")) {
let rS = (self.leftline as! rString)
if rS.text != "" {
rS.fontName = "HelveticaNeue-Bold"
rS.size = 15
rS.color = UIColor(red:0.01, green:0.48, blue:1.00, alpha:1.0)
let l3 = rS.getLabel()
l3.frame = CGRect(x: width - (rightMargin + Int(rS.getFont().lineWidth(rS.text)) + 15), y: height/2 - (Int(rS.getFont().lineHeight) + 10)/2, width: Int(rS.getFont().lineWidth(rS.text)) + 15, height: Int(rS.getFont().lineHeight) + 10)
l3.backgroundColor = UIColor(red:0.94, green:0.94, blue:0.97, alpha:1.0)
l3.layer.masksToBounds = true
l3.layer.borderWidth = 2
l3.layer.borderColor = UIColor(red:0.94, green:0.94, blue:0.97, alpha:1.0).cgColor
l3.layer.cornerRadius = rS.getFont().lineHeight/1.2
l3.textAlignment = .center
v.addSubview(l3)
}
}
//GestureRecognizer
v.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.oIT(_:))))
v.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(self.oILP(_:))))
v.restorationIdentifier = self.id
return v;
}
#objc func oIT(_ sender: UITapGestureRecognizer) {
print("Tap")
self.onItemTap(sender)
}
#objc func oILP(_ sender: UILongPressGestureRecognizer) {
print("LongPress")
self.onItemLongPress(sender)
}
static func ==(lhs: UIItemView, rhs: UIItemView) -> Bool {
return lhs === rhs
}
}
TIPS : UIItemView contains the function getView() which returns a specific UIView
The problem :
Everything work properly, when I load the ViewController (where there is the UIScrollView) every UIView's are build like I want, and I can interact with the UIView by the UITapGestureRecognizer or the UILongPressGestureRecognizer (the function is called as expected)
BUT
When I call the function updateItems() a second time, without reload the ViewController, the items change as expected but the UITapGestureRecognizer and the UILongPressGestureRecognizer don't work any more.
I hope you can help me :D
If information are missing for you to understand the problem, please let me know ;)

Autoresize infowindow from xib file depended from the content in swift

I try to resize my custom infowindow which is created in a xib file from a UIView.The width depends from content of the window, but i have not find any solution.I tried everything in the storyboard but nothing happens.I have upload a screenshot to see my problem:
Here is my code from the UIView of the xib
public protocol nonPaidDelegate: class {
func didTapMapsSelectButton()
}
class MapInfoWindow: UIView {
#IBOutlet weak var titleInfo: UILabel!
#IBOutlet weak var adressInfo: UILabel!
#IBOutlet weak var buttonAction: UIButton!
open var delegate:nonPaidDelegate?
#IBAction func didTapInButton(_ sender: Any) {
self.delegate?.didTapMapsSelectButton()
print("button tapped")
}
class func instanceFromNib() -> UIView {
return UINib(nibName: "MapInfoWindowView", bundle: nil).instantiate(withOwner: self, options: nil).first as! UIView
}
In my viewcontroller i call the MapInfoWindow
var infoWindow = MapInfoWindow()
infoWindow = loadNiB()
and i create the infoWindow UIView for the marker:
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
if let venueItem = marker.userData as? Venue {
infoWindow.titleInfo?.text = venueItem.name
infoWindow.adressInfo?.text = venueItem.locationName
NSLog(venueItem.name!)
} else {
NSLog("Did tap a normal marker")
}
return UIView()
}
}
You can achieve your goal programmatically like this,I have used two label(titleLabel & snippetLabel):
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
let infoWindowView = UIView()
let titleStringWidth = marker.title?.widthOfString(usingFont: UIFont.boldSystemFont(ofSize: 13.0))
var infoWidth = 0
if titleStringWidth!+10>self.view.frame.size.width - 50 {
infoWindowView.frame.size.width = self.view.frame.size.width - 50
infoWidth = Int(self.view.frame.size.width - 50.0)
}else {
infoWindowView.frame.size.width = titleStringWidth!+10
infoWidth = Int(titleStringWidth!)+10
}
infoWindowView.frame.size.width = self.view.frame.size.width - 50
infoWindowView.backgroundColor = UIColor.white
let titleLabel = UILabel()
titleLabel.frame.size.width = infoWindowView.frame.size.width-10
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.font = UIFont.boldSystemFont(ofSize: 13.0)
titleLabel.frame.origin.x = 3
titleLabel.frame.origin.y = 5
titleLabel.text = "your text"
titleLabel.textAlignment = .center
titleLabel.sizeToFit()
let actualNumberOfLinesForTiltle = titleLabel.numberOfVisibleLines
titleLabel.frame.size.height = CGFloat(actualNumberOfLinesForTiltle*20)
let snippetLabel = UILabel()
snippetLabel.frame.size.width = infoWindowView.frame.size.width-10
snippetLabel.numberOfLines = 0
snippetLabel.lineBreakMode = .byWordWrapping
snippetLabel.font = UIFont.boldSystemFont(ofSize: 13.0)
snippetLabel.text = "your text"
snippetLabel.textAlignment = .center
snippetLabel.sizeToFit()
let snippet_y = 20*actualNumberOfLinesForTiltle+10
let actualNumberOfLinesForSnippet = snippetLabel.numberOfVisibleLines
snippetLabel.frame.origin.x = 3
snippetLabel.frame.origin.y = CGFloat(snippet_y)
snippetLabel.frame.size.height = CGFloat(actualNumberOfLinesForSnippet*20)
let visibleHeightOfView = 15+actualNumberOfLinesForTiltle*20+actualNumberOfLinesForSnippet*20
infoWindowView.frame = CGRect(x: 0, y: 0, width: infoWidth, height: visibleHeightOfView)
infoWindowView.addSubview(titleLabel)
infoWindowView.addSubview(snippetLabel)
return infoWindowView
}
and add this extension
extension UILabel {
var numberOfVisibleLines: Int {
let textSize = CGSize(width: CGFloat(self.frame.size.width), height: CGFloat(MAXFLOAT))
let rHeight: Int = lroundf(Float(self.sizeThatFits(textSize).height))
let charSize: Int = lroundf(Float(self.font.pointSize))
return rHeight / charSize
}
}
extension String {
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSFontAttributeName: font]
let size = self.size(attributes: fontAttributes)
return size.width
}

how to define a label by a tag

i try a make a cloud of tag, and i have trouble with how to determine which label was pressed, for to the change color it. if i use like viewq.viewWithTag(1) it work but how i can understand what a label i press ? for change value. Maybe i need a make class ? because i want (if u press once, set color red and some action, if again it set blue color again and make some action)
//
// ViewController.swift
// weqddwqd
//
// Created by Jacket on 4/2/18.
// Copyright © 2018 TryFit. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var viewq: UIView!
var arrq: [String] = ["Hello", "World", "of", "Tags"]
var tags: [Int] = Array()
override func viewDidLoad() {
super.viewDidLoad()
createTagsLabel(arrq)
}
}
extension ViewController {
func createTagsLabel(_: [String]) {
var xPos:CGFloat = 15.0
var ypos: CGFloat = 130.0
var tag: Int = 0
for word in arrq {
let width = word.widthOfString(usingFont: UIFont(name:"verdana", size: 13.0)!)
let checkWholeWidth = CGFloat(xPos) + CGFloat(width) + CGFloat(13.0) + CGFloat(25.5)
if checkWholeWidth > UIScreen.main.bounds.size.width - 30.0 {
xPos = 15.0
ypos = ypos + 29.0 + 8.0
}
let textlable = UILabel(frame: CGRect(x: xPos, y: ypos, width: width + 18, height: 18))
textlable.layer.borderWidth = 1.8
textlable.layer.cornerRadius = 8
textlable.layer.borderColor = UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0).cgColor
textlable.textColor = UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0)
textlable.text = word
textlable.font = UIFont(name: "verdana", size: 13.0)
textlable.textAlignment = .center
textlable.isUserInteractionEnabled = true
ypos = ypos + 25
textlable.tag = tag
tags.append(tag)
tag = tag + 1
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapFunction(_:)))
//textlable.addTarget(self, action: #selector(tapFunction(_:)), for: .touchUpInside)
textlable.addGestureRecognizer(tap)
viewq.addSubview(textlable)
}
}
func tapFunction(_ recognizer: UITapGestureRecognizer) {
print(viewq.viewWithTag(1))
let tag = viewq.viewWithTag(1) as! UILabel
tag.layer.borderColor = UIColor .red.cgColor
tag.textColor = UIColor .red
print("Added")
}
}
extension String {
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSFontAttributeName: font]
let size = self.size(attributes: fontAttributes)
return size.width
}
func heightOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSFontAttributeName: font]
let size = self.size(attributes: fontAttributes)
return size.height
}
}
Your tapFunction can easily get the tapped view from the gesture. No tags required:
func tapFunction(_ recognizer: UITapGestureRecognizer) {
if let tappedLabel = recognizer.view as? UILabel {
tappedLabel.layer.borderColor = UIColor.red.cgColor
tappedLabel.textColor = .red
print("Added")
}
}

Changing textColor with #IBInspectable inside array of Labels

I have weekDaysContainerView subclassing UIView, and trying to change textColor with #IBInspectable. Interface Builder show options to change color inside of it, but it never does in real app.
var weekdays = [UILabel]()
#IBInspectable var dayLabelColor: UIColor = UIColor.gray {
didSet {
for day in weekdays {
day.textColor = dayLabelColor
}
}
}
lazy var dayLabelContainerView : UIView = {
let formatter = DateFormatter()
let view = UIView()
for index in 1...7 {
let day: NSString = formatter.weekdaySymbols[index % 7 ] as NSString
let weekdayLabel = UILabel()
weekdayLabel.text = day.substring(to: 3).uppercased()
weekdayLabel.textColor = UIColor.gray
weekdayLabel.textAlignment = NSTextAlignment.center
view.addSubview(weekdayLabel)
weekdays.append(weekdayLabel)
}
addSubview(view)
return view
}()

UIButton Action doesn't call in Swift?

In my project I have create the Left View and Right View, its dynamically show two different Views, Left View side create firstView and the FirstView inside show Title, Comments, Image and Video. And Also RightView side create secondView inside show Title,Comments, Image and Video. Image and Video show only some of the Views. The design is fully created programmatically, my design is given below,
My problem is play button(UIButton) Action not Called why?
I don't know,
my code is give below, UIButton Name: btnPlay, Action Name: buttonAction:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scrollViewBase: UIScrollView!
var leftView = UIView()
var rightView = UIView()
var wholeYLeft = CGFloat()
var wholeYRight = CGFloat()
let btnPlay = UIButton()
var myArrayOfDict: NSArray = [
["Title": "MacBook", "Text": "Our goal with MacBook was to do the impossible: engineer a full-sized experience into the lightest and most compact Mac notebook ever. That meant reimagining every element to make it not only lighter and thinner but also better.", "Image":"MacBook1","video":""],
["Title": "OS X", "Text": "OS X is the operating system that makes it possible to do all the things you do on a Mac.", "Image":"","video":""],
["Title": "MacBook Pro", "Text": "Now with the force Touch trackpad,longer battery life and faster flash storage", "Image":"MacBookPro1","video":""],
["Title": "Mac Mini", "Text": "Mac mini is an affordable powerhouse that packs the entire Mac experience into a 19.7cm-square frame. Just connect your own display, keyboard and mouse, and you’re ready to make big things happen.", "Image":"Mini","video":""],
["Title": "iMac", "Text": "The idea behind iMac has never wavered: to craft the ultimate desktop experience. The best display, paired with high-performance processors, graphics and storage ", "Image":"","video":""],
["Title": "MacBook Air", "Text": "The 11-inch MacBook Air lasts up to 9 hours between charges and the 13-inch model lasts up to an incredible 12 hours. So from your morning coffee till your evening commute, you can work unplugged.", "Image":"VideoThumn","video":"Official Apple MacBook Air Video YouTube.mp4"]
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "Dynamic Cell"
leftView.frame = CGRectMake(0, 0, self.view.frame.width/2, self.view.frame.height)
rightView.frame = CGRectMake(self.view.frame.width/2, 0, self.view.frame.width/2, self.view.frame.height)
// leftView.backgroundColor = UIColor.lightGrayColor()
// rightView.backgroundColor = UIColor.grayColor()
self.scrollViewBase.addSubview(leftView)
self.scrollViewBase.addSubview(rightView)
self.callViewMethod()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func callViewMethod() {
var yFloatLeft : CGFloat! = 5
var yFloatRight : CGFloat! = 5
wholeYLeft = 0
wholeYRight = 0
for var i = 0; i < myArrayOfDict.count; i++ {
let isCheckImage = myArrayOfDict[i].valueForKey("Image") as! String
let isCheckVideo = myArrayOfDict[i].valueForKey("video") as! String
let str = myArrayOfDict[i].valueForKey("Text") as? String
let boundingRectHeight = str!.boundingRectWithSize(CGSizeMake(self.leftView.frame.width-10, CGFloat.max),
options:NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: UIFont(name: "Arial", size: 14.0)!], context:nil).size.height + 60.0
if(i%2 == 0) {
let firstView = UIView()
print(yFloatLeft)
if(isCheckImage == "") {
firstView.frame = CGRectMake(5, yFloatLeft, self.leftView.frame.width-10, 30 + boundingRectHeight)
} else {
firstView.frame = CGRectMake(5, yFloatLeft, self.leftView.frame.width-10, 180 + boundingRectHeight)
}
// firstView.backgroundColor = UIColor.redColor()
firstView.layer.borderWidth = 2.0
firstView.layer.borderColor = UIColor.lightGrayColor().CGColor
leftView.addSubview(firstView)
let lblTitle = UILabel()
lblTitle.frame = CGRectMake(0, 0, self.leftView.frame.width-10, 30)
lblTitle.textAlignment = NSTextAlignment.Center
lblTitle.text = myArrayOfDict[i].valueForKey("Title") as? String
let lblText = lblInset()
lblText.frame = CGRectMake(0, 30, self.leftView.frame.width-10, boundingRectHeight)
lblText.text = myArrayOfDict[i].valueForKey("Text") as? String
lblText.numberOfLines = 0
lblText.lineBreakMode = .ByWordWrapping
lblText.font = UIFont(name: "Arial", size: 16)
lblText.textAlignment = NSTextAlignment.Justified
let mainImageView = UIImageView()
if(isCheckImage == "") {
mainImageView.hidden = true
yFloatLeft = yFloatLeft + 30 + boundingRectHeight + 10
} else {
mainImageView.hidden = false
mainImageView.frame = CGRectMake(0, 30 + boundingRectHeight, self.leftView.frame.width-10, 150)
mainImageView.image = UIImage(named: (myArrayOfDict[i].valueForKey("Image") as? String)!)
if(isCheckVideo == "") {
btnPlay.hidden = true
} else {
btnPlay.hidden = false
btnPlay.frame = CGRectMake((mainImageView.frame.width/2)-10, (mainImageView.frame.height/2)-10, 30, 30)
btnPlay.backgroundColor = UIColor.blackColor()
btnPlay.userInteractionEnabled = true
btnPlay.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
btnPlay.setImage(UIImage(named: "Play"), forState: .Normal)
mainImageView.addSubview(btnPlay)
}
yFloatLeft = yFloatLeft + 30 + boundingRectHeight + 160
}
firstView.addSubview(lblTitle)
firstView.addSubview(lblText)
firstView.addSubview(mainImageView)
firstView.bringSubviewToFront(btnPlay)
} else {
let secondView = UIView()
if(isCheckImage == "") {
secondView.frame = CGRectMake(5, yFloatRight, self.rightView.frame.width-10, 30 + boundingRectHeight)
} else {
secondView.frame = CGRectMake(5, yFloatRight, self.rightView.frame.width-10, 180 + boundingRectHeight)
}
// secondView.backgroundColor = UIColor.purpleColor()
secondView.layer.borderWidth = 2.0
secondView.layer.borderColor = UIColor.lightGrayColor().CGColor
rightView.addSubview(secondView)
let lblTitle = UILabel()
lblTitle.frame = CGRectMake(0, 0, self.leftView.frame.width-10, 30)
lblTitle.textAlignment = NSTextAlignment.Center
lblTitle.text = myArrayOfDict[i].valueForKey("Title") as? String
let lblText = lblInset()
lblText.frame = CGRectMake(0, 30, self.leftView.frame.width-10, boundingRectHeight)
lblText.text = myArrayOfDict[i].valueForKey("Text") as? String
lblText.numberOfLines = 0
lblText.lineBreakMode = .ByWordWrapping
lblText.font = UIFont(name: "Arial", size: 16)
lblText.textAlignment = NSTextAlignment.Justified
let mainImageView = UIImageView()
if(isCheckImage == "") {
mainImageView.hidden = true
yFloatRight = yFloatRight + 30 + boundingRectHeight + 10
} else {
mainImageView.hidden = false
mainImageView.frame = CGRectMake(0, 30 + boundingRectHeight, self.leftView.frame.width-10, 150)
mainImageView.image = UIImage(named: (myArrayOfDict[i].valueForKey("Image") as? String)!)
if(isCheckVideo == "") {
btnPlay.hidden = true
} else {
btnPlay.hidden = false
btnPlay.frame = CGRectMake((mainImageView.frame.width/2)-10, (mainImageView.frame.height/2)-10, 30, 30)
btnPlay.userInteractionEnabled = true
btnPlay.backgroundColor = UIColor.blackColor()
btnPlay.setImage(UIImage(named: "Play"), forState: .Normal)
btnPlay.addTarget(self, action: Selector("buttonAction:"), forControlEvents: .TouchUpInside)
mainImageView.addSubview(btnPlay)
}
yFloatRight = yFloatRight + 30 + boundingRectHeight + 160
}
secondView.addSubview(lblTitle)
secondView.addSubview(lblText)
secondView.addSubview(mainImageView)
secondView.bringSubviewToFront(btnPlay)
}
wholeYLeft = yFloatLeft
wholeYRight = yFloatRight
}
print(wholeYLeft)
print(wholeYRight)
leftView.frame = CGRectMake(0, 0, self.view.frame.width/2, wholeYLeft)
rightView.frame = CGRectMake(self.view.frame.width/2, 0, self.view.frame.width/2, wholeYRight)
if(wholeYRight > wholeYLeft) {
self.scrollViewBase.contentSize = CGSize(width:self.view.frame.width, height: wholeYRight)
} else {
self.scrollViewBase.contentSize = CGSize(width:self.view.frame.width, height: wholeYLeft)
}
}
func buttonAction(sender:UIButton!) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("PlayViewController") as! PlayViewController
controller.lblTitle.text = myArrayOfDict[5].valueForKey("Title") as? String
controller.lblComments.text = myArrayOfDict[5].valueForKey("Text") as? String
self.presentViewController(controller, animated: true, completion: nil)
}
}
I got an Answer, In UIButton (btnPlay) add subview give UIImageView, my problem is mainImageView.addSubview(btnPlay), so change the subView to UIView instead of UIImageView correct code is
secondView.addSubview(btnPlay)
secondView.bringSubviewToFront(btnPlay)
its working for me
You have to enable user interaction for dynamically created Imageview, so write one more line after,
let mainImageView = UIImageView()
mainImageView.userInteractionEnabled = true
Hope this will work.
You have to tag the button then only it can recognise which button is that
btnPlay.tag = 1

Resources