25

次のコードは私の問題を表しています:(空のテンプレートでXcodeプロジェクトを作成し、main.mファイルの内容を置き換え、AppDelegate.h/.mファイルを削除してビルドできるという点で自己完結型です)

//
//  main.m
//  CollectionViewProblem
//


#import <UIKit/UIKit.h>

@interface Cell : UICollectionViewCell

@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) UILabel *label;

@end

@implementation Cell
 - (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        self.label = [[UILabel alloc] initWithFrame:self.bounds];
        self.label.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.label.backgroundColor = [UIColor greenColor];
        self.label.textAlignment = NSTextAlignmentCenter;

        self.button = [UIButton buttonWithType:UIButtonTypeInfoLight]; 
        self.button.frame = CGRectMake(-frame.size.width/4, -frame.size.width/4, frame.size.width/2, frame.size.width/2);
        self.button.backgroundColor = [UIColor redColor];
        [self.button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:self.label];
        [self.contentView addSubview:self.button];
    }
    return self;
}


// Overriding this because the button's rect is partially outside the parent-view's bounds:
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    if ([super pointInside:point withEvent:event])
    {
        NSLog(@"inside cell");
        return YES;
    }
    if ([self.button
         pointInside:[self convertPoint:point
                                 toView:self.button] withEvent:nil])
    {
        NSLog(@"inside button");
        return YES;
    }

    return NO;
}


- (void)buttonClicked:(UIButton *)sender
{
    NSLog(@"button clicked!");
}
@end

@interface ViewController : UICollectionViewController

@end

@implementation ViewController

// (1a) viewdidLoad:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.collectionView registerClass:[Cell class] forCellWithReuseIdentifier:@"ID"];
}

// collection view data source methods ////////////////////////////////////

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 100;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ID" forIndexPath:indexPath];
    cell.label.text = [NSString stringWithFormat:@"%d", indexPath.row];
    return cell;
}
///////////////////////////////////////////////////////////////////////////

// collection view delegate methods ////////////////////////////////////////

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"cell #%d was selected", indexPath.row);
}
////////////////////////////////////////////////////////////////////////////
@end


@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    ViewController *vc = [[ViewController alloc] initWithCollectionViewLayout:layout];


    layout.itemSize = CGSizeMake(128, 128);
    layout.minimumInteritemSpacing = 64;
    layout.minimumLineSpacing = 64;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(32, 32, 32, 32);


    self.window.rootViewController = vc;

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

@end


int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

基本的に、コレクション ビューを使用してスプリングボード タイプの UI を作成しています。私のUICollectionViewCellサブクラス ( Cell ) には、部分的にセルのcontentView (つまり、そのスーパービュー) の境界外にあるボタンがあります。

問題は、ボタンのcontentView境界外 (基本的にはボタンの 3/4) の任意の部分をクリックしても、ボタン アクションが呼び出されないことです。contentViewと重なるボタンの部分をクリックした場合にのみ、ボタンのアクション メソッドが呼び出されます。

ボタンのタッチが認識されるように、 Cell-pointInside:withEvent:のメソッドもオーバーライドしました。しかし、それはボタンクリックの問題には役立たなかった。

collectionViewがタッチを処理する方法と関係があるのではないかと推測していますが、何がわかりません。UICollectionViewUIScrollViewのサブクラスであることはわかっており、部分的に重なっているボタンを含むビュー (サブビューをスクロール ビューにする) をオーバーライド-pointInside:withEvent:するとボタン クリックの問題が解決されることを実際にテストしましたが、ここでは機能しませんでした。

何か助けはありますか?

** 追加: 記録として、問題に対する私の現在の解決策は、セルに外観を与えるcontentViewに小さなサブビューを挿入することです。削除ボタンはcontentViewに追加され、その rect は実際には contentView の境界内にありますが、セルの表示部分 (つまり、挿入サブビュー) と部分的にしか重なりません。それで、私が望んでいた効果が得られ、ボタンは適切に機能しています. しかし、上記の元の実装の問題についてはまだ興味があります。

4

9 に答える 9

13

Interface Builder で、オブジェクトを UICollectionViewCell として設定しましたか? 誤って一度UIViewを設定し、それに正しいUICollectionViewCellクラスを割り当てた後...しかし、これを行うと(ボタン、ラベルなど)はcontentViewに追加されないため、応答しません...

したがって、インターフェイスを描画するときに UICollectionViewCell オブジェクトを取得するよう IB で思い出してください :)

于 2013-01-03T19:17:44.363 に答える
5

迅速なバージョン:

override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {

    //From higher z- order to lower except base view;

    for (var i = subviews.count-2; i >= 0 ; i--){
        let newPoint = subviews[i].convertPoint(point, fromView: self)
        let view = subviews[i].hitTest(newPoint, withEvent: event)
        if view != nil{
            return view
        }
    }

    return super.hitTest(point, withEvent: event)

}

それだけです...すべてのサブビューについて

于 2015-05-27T09:16:43.010 に答える
3

サブクラス化されたUICollectionViewCell.mファイルで次のように作成されたボタンへのタッチを正常に受信しています。

- (id)initWithCoder:(NSCoder *)aDecoder
    {
    self = [super initWithCoder:aDecoder];
    if (self)
    {

    // Create button

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 100, 100); // position in the parent view and set the size of the button
    [button setTitle:@"Title" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"animage.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];

    // add to contentView
    [self.contentView addSubview:button];
    }
    return self;
}

ストーリーボードに追加されたボタンが機能しないことに気付いた後、コードにボタンを追加しました。これが最新のXcodeで修正されているかどうかはわかりません。

お役に立てば幸いです。

于 2012-11-04T20:52:40.210 に答える
3

正確には迅速な変換ではない元の回答の 2 つの迅速な変換が表示されます。ですからSwift 4、元の回答を変換して、誰もが使用できるようにしたいだけです。コードを に貼り付けるだけですsubclassed UICollectionViewCellcloseButton独自のボタンで変更することを確認してください。

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
    var view = closeButton.hitTest(closeButton.convert(point, from: self), with: event)
    if view == nil {
        view = super.hitTest(point, with: event)
    }

    return view
}

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    if super.point(inside: point, with: event) {
        return true
    }

    return !closeButton.isHidden && closeButton.point(inside: closeButton.convert(point, from: self), with: event)
}
于 2018-04-16T12:49:46.153 に答える
1

uicollectionview セルの境界外に削除ボタンを配置しようとすると、同様の問題が発生し、タップ イベントに応答するように継ぎ目がありませんでした。

私がそれを解決した方法は、コレクションに UITapGestureRecognizer を配置し、タップが発生したときに次のコードを実行することでした

//this works also on taps outside the cell bouns, im guessing by getting the closest cell to the point of click.

NSIndexPath* tappedCellPath = [self.collectionView indexPathForItemAtPoint:[tapRecognizer locationInView:self.collectionView]]; 

if(tappedCellPath) {
    UICollectionViewCell *tappedCell = [self.collectionView cellForItemAtIndexPath:tappedCellPath];
    CGPoint tapInCellPoint = [tapRecognizer locationInView:tappedCell];
    //if the tap was outside of the cell bounds then its in negative values and it means the delete button was tapped
    if (tapInCellPoint.x < 0) [self deleteCell:tappedCell]; 
}
于 2013-04-28T09:20:18.013 に答える